首页 > 解决方案 > Utilities.formatDate 使用 Array.map 返回错误的日期

问题描述

arr我创建了一个函数,从 2013 年 1 月 1 日开始以 1 个月为增量生成日期数组,一直持续到现在。

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


该函数正确生成arr,如下所示:

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

但是当我登录时arr.map(formatDate),从第 4 天开始,我没有得到相同的日期:

Jan-01,Feb-01,Mar-01,Mar-31,Apr-30...

任何想法为什么 Utilities.formatDate 搞砸了日期?

标签: javascriptdategoogle-apps-scriptwhile-loop

解决方案


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


推荐阅读