gpt4 book ai didi

javascript - 如何使用 Google Apps 脚本获取上个月日期的正确格式

转载 作者:行者123 更新时间:2023-11-28 19:04:47 25 4
gpt4 key购买 nike

使用 Google Apps 脚本,我获取上个月的第一个和最后一个日期,然后将格式更改为 GMT“yyyy-MM-dd”

var todayDate = new Date();

var lastDate = function getLastDate() {
var d = todayDate;
d.setDate(0);
return Utilities.formatDate(d, 'GMT', 'yyyy-MM-dd');
}

var firstDate = function getFirstDate() {
var e = todayDate;
e.setMonth(e.getMonth() - 1);
e.setDate(1);
return Utilities.formatDate(e, 'GMT', 'yyyy-MM-dd');
}

但我收到一条错误消息:

无效值 ' function getLastDate() { var d = TodayDate; d.setDate(0); return Utilities.formatDate(e, "GMT", "yyyy-MM-dd"); } '.值必须与以下正则表达式匹配:“[0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo)”

有人可以帮忙吗?

最佳答案

您似乎期望这些变量包含日期,但您声明它们的方式并未将关联函数的返回值分配给它们,而是将函数本身分配给它们。

您期望 lastDate 包含:

2015-07-31

但它实际上包含:

function getLastDate() { var d = todayDate; d.setDate(0); return Utilities.formatDate(e, "GMT", "yyyy-MM-dd"); } 

您需要将赋值与声明分开:

var todayDate = new Date();

function getLastDate() {
var d = todayDate;
d.setDate(0);
return Utilities.formatDate(d, 'GMT', 'yyyy-MM-dd');
}
var lastDate = getLastDate();

function getFirstDate() {
var e = todayDate;
e.setMonth(e.getMonth() - 1);
e.setDate(1);
return Utilities.formatDate(e, 'GMT', 'yyyy-MM-dd');
}
var firstDate = getFirstDate();

// check values
Logger.log(lastDate);
Logger.log(firstDate);

但看起来我们甚至不需要保留这些功能。我们可以把它们变成IIFE 。我们或许还应该避免重复使用相同的 Date 对象:

var lastDate = (function() {
var d = new Date();
d.setDate(0);
return Utilities.formatDate(d, 'GMT', 'yyyy-MM-dd');
})();

var firstDate = (function() {
var d = new Date();
d.setMonth(d.getMonth() - 1);
d.setDate(1);
return Utilities.formatDate(d, 'GMT', 'yyyy-MM-dd');
})();

// check values
Logger.log(lastDate);
Logger.log(firstDate);

关于javascript - 如何使用 Google Apps 脚本获取上个月日期的正确格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com