【问题标题】:Utilities.formatDate returning the wrong date with Array.mapUtilities.formatDate 使用 Array.map 返回错误的日期
【发布时间】:2023-03-29 04:09:01
【问题描述】:

我创建了一个函数来生成日期数组 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 搞砸了日期?

【问题讨论】:

  • Jan 01 2013 00:00:00 GMT-0700 (MST) 在格式化为 MMM-dd 时应为 Jan-01
  • 前三个日期看起来不错,但之后日期开始变得奇怪。
  • 啊,这是夏令时。您可以看到从 3 月到 4 月的时区偏移量变化。由于您的日期时间设置为 00:00:00 并且您格式化为旧时区,因此您会损失一个小时并回滚到上个月。
  • 愚蠢的夏令时。接得好。谢谢@VLAZ
  • 你不应该依赖new Date(string)跨浏览器甚至同一浏览器的版本返回正确的日期,除非版本是最新的并且string的格式是yyyy-MM-ddyyyy-MM-ddTHH:mm:ss .见Why does Date.parse give incorrect results?

标签: javascript date google-apps-script while-loop


【解决方案1】:

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

【讨论】:

  • 谢谢@Ankit。我可以通过将初始日期时间设置为 12:00 来解决该问题,这样它就不会受到夏令时的影响。
  • 太好了,是的,这可以是解决此问题的另一种选择。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 2013-11-08
  • 2013-09-04
相关资源
最近更新 更多