如何获得正确的格式日期在前一个月与谷歌应用程序脚本

How to get the right format for dates in the previous month with Google Apps Script

本文关键字:一个 脚本 应用程序 谷歌 何获得 格式 日期      更新时间:2023-09-26

使用Google Apps Script,我从上个月获得第一个和最后一个日期,然后将格式更改为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');
    }

但是我得到一个错误声明:

"无效值"函数getLastDate() {var d = todayDate;d.setDate (0);返回工具。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);

但是看起来我们甚至不需要保留这些函数。我们可以把它们变成生命。我们可能还应该避免重用相同的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);

如果您想获取上个月的数据并将其设置为西班牙语,请查看此…

var previousMonth = (function() {
    var d = new Date();
    d.setMonth(d.getMonth() - 1);
    var getLastMonth = Utilities.formatDate(d,Session.getScriptTimeZone(),"MMMM");
    var translateMonthIntoSpanish = LanguageApp.translate (getLastMonth,'en','es');
    var titleCaseMonth = translateMonthIntoSpanish.charAt(0).toUpperCase() + translateMonthIntoSpanish.slice(1);
    return titleCaseMonth;
})();
Logger.log(previousMonth);
相关文章: