如何使用应用脚本以"yyyy-mm-dd"格式获取当前周和月的第一个日期和最后一个日期



我正试图使用谷歌应用程序脚本以yyyy-mm-dd的格式计算出本周的第一个日期和最后一个日期以及本月的第一个日子和最后一天。Date()对我来说似乎是一个困难的对象,因此寻求建议。请考虑一下,在世界的这一地区,周六是一周的开始日,周五是一周结束日。

获取本周的第一个(星期六(和最后一个(星期五(日期

您可以使用Date.getDay()来获取一周中的当前日期(0=周日,1=周一等(。但没有方法Date.setDay(),所以我们需要做一些数学运算来计算最近的周六是多少天前,并使用Date.setDate():

// Get the Date for the Saturday on or preceding the current date.
var saturday = new Date(); // Today
var day = date.getDay(); // Day of week (0-6)
var newDay = date.getDate() - ((day + 1) % 7);  // The day of the month we want.
saturday.setDate(newDay); // Our date object for Saturday.

(day + 1) % 7计算要减去多少天;例如,如果今天是星期日(day=0(,我们需要返回一天:(0 + 1) % 7 = 1。但如果今天是星期六(第6天(,我们得到(6 + 1) % 7 = 0,并且不减去任何一天。

寻找即将到来的星期五的程序是类似的,但我们增加天数而不是减去:

// Get the Date for the Friday on or after the given date.
var friday = new Date(date); // today
var day = date.getDay();
var diff = date.getDate() + ((5 - day) % 7); 
friday.setDate(diff);

获取本月的第一个和最后一个日期

使用setDate()更简单,因为它将一个月的哪一天作为参数。

var firstOfMonth = new Date(); // today
firstOfMonth.setDate(1); // Sets the day to the first of the month

为了获得本月的最后一天,我们继续一个月,然后回到上个月的最后天(本月最后一天(:

var lastOfMonth = new Date(); 
lastOfMonth.setMonth(lastOfMonth.getMonth()+1);  // Go ahead one month
lastOfMonth.setDate(0); // Sets to 1 day before the first of the month, i.e. the last of this month. 

转换为"yyyy-mm-dd"格式

谷歌应用程序脚本有一个内置的日期格式化方法:Utilities.formatDate(date, timezone, format)

date是Date对象,timezone是TZ数据库中的字符串,format是SimpleDateFormat 中的字符串

例如:

var formattedDate = Utilities.formatDate(friday, 'America/Denver', 'yyyy-MM-dd');

(注意大写MM表示月份,因为mm表示分钟。(

您可以使用toLocaleString("sv SE"(将日期转换为所需的格式yyyy-mm-dd

试试这个:

const today = new Date(); 
const firstWeekD = today.getDate() - today.getDay()-1; 
const lastWeekD = firstWeekD + 6; 
const firstdayOfWeek = new Date(today.setDate(firstWeekD)).toLocaleString("sv-SE").slice(0,10);
const lastdayOfWeek = new Date(today.setDate(lastWeekD)).toLocaleString("sv-SE").slice(0,10);
const date = new Date();
const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).toLocaleString("sv-SE").slice(0,10);
const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).toLocaleString("sv-SE").slice(0,10);

console.log(firstdayOfWeek); // first day of the week - Saturday
console.log(lastdayOfWeek); // last day of the week - Friday
console.log(firstDayOfMonth) // first day of the month
console.log(lastDayOfMonth) // last day of the month

最新更新