GKyle
GKyle

Reputation: 679

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

Using Google Apps Script, I am getting the first and last date from the previous month and then change the format to 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');
    }

But I get an error stating:

"Invalid value ' function getLastDate() { var d = todayDate; d.setDate(0); return Utilities.formatDate(e, "GMT", "yyyy-MM-dd"); } '. Values must match the following regular expression: '[0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo)'"

Can someone please help?

Upvotes: 1

Views: 4733

Answers (2)

Josh Tule
Josh Tule

Reputation: 31

If you want to get previous month and locale it into spanish, check this out..

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

Upvotes: 3

spenibus
spenibus

Reputation: 4409

You seem to be expecting those variables to contain dates, but the way you declare them does not assign to them the return value of the associated functions but the functions themselves.

You expect lastDate to contain:

2015-07-31

but it actually contains:

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

You need to separate the assignment from the declaration:

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

But it looks like we don't even really need to keep those functions. We can turn them into IIFE. We should probably also avoid reusing the same Date object:

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

Upvotes: 3

Related Questions