Reputation: 11
I created a function to generate an array of dates arr
in 1-month increments beginning at 1/1/2013 and going until now.
function getDateRange() {
var start = new Date('1/1/2013');
var today = new Date();
var arr = [start];
var next = new Date(start);
while (next < today) {
arr.push(next);
next = new Date(next.setMonth(next.getMonth() + 1));
}
Logger.log(arr);
Logger.log(arr.map(formatDate));
}
function formatDate(d) {
return Utilities.formatDate(d, 'MST', 'MMM-dd');
}
The function correctly generates arr
, which looks like the following:
Jan 01 2013 00:00:00 GMT-0700 (MST),Fri Feb 01 2013 00:00:00 GMT-0700 (MST),Fri Mar 01 2013 00:00:00 GMT-0700 (MST),Mon Apr 01 2013 00:00:00 GMT-0600 (MDT),Wed May 01 2013 00:00:00 GMT-0600 (MDT)...
but then when I log arr.map(formatDate)
, I don't get the same dates starting at the 4th date:
Jan-01,Feb-01,Mar-01,Mar-31,Apr-30...
Any ideas why Utilities.formatDate is screwing up the dates?
Upvotes: 1
Views: 240
Reputation: 3122
function getDateRange() {
var start = new Date('1/1/2013');
var today = new Date();
var arr = [];
do {
arr.push(start);
start = new Date(start.setDate(start.getDate() + 1));
} while (start < today)
console.log(arr);
console.log(arr.map(formatDate));
}
function formatDate(date) {
return date.toLocaleString("en-us", {
month: "short",
timeZone: 'UTC'
}) + "-" + date.toLocaleString("en-us", {
day: "numeric",
timeZone: 'UTC'
});
}
Upvotes: 3