2015-08-09 51 views
0

使用Google Apps腳本,我可以獲取上個月的第一個和最後一個日期,然後將格式更改爲GMT'yyyy-MM-dd'如何使用Google Apps腳本獲取上月的日期格式

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(){風險d = todayDate; d.setDate(0);返回Utilities.formatDate(例如, 「GMT」 ,「yyyy-MM-dd」);}'。值必須匹配以下正則表達式:'[0-9] {4} - [0-9] {2} - [0-9] {2} |今天|昨天| [0-9] +(daysAgo)'

有人可以幫忙嗎?

回答

1

您似乎期望這些變量包含日期,但是您聲明它們的方式不會爲其分配相關函數的返回值,而是函數本身。

您希望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。我們可能也應該避免重複使用相同的物體:

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); 
+0

想要使用Logger.log嗎? – enano2054

相關問題