google-apps-script - 如何格式化这个日期字符串以便谷歌脚本识别它?

标签 google-apps-script

我收到一个 json feed,其日期字符串格式如下:

//2012-08-03T23:00:26-05:00

我原以为我可以将其传递给一个新的日期

var dt = new Date("2012-08-03T23:00:26-05:00");

这适用于 jsfiddle,但不适用于 google 脚本。它返回无效日期。看完this post我认识到这可能是 GAS 解释日期字符串的方式,所以现在我不确定如何重新格式化日期以使其正常工作。

有没有最好的方法来重新格式化该日期字符串,以便 GAS 可以将其识别为日期?

最佳答案

Google Apps 脚本使用特定版本的 JavaScript ( ECMA-262 3rd Edition ),并且您已发现无法解析 ISO 8601 格式的日期/时间。以下是我在许多应用程序脚本中使用的修改后的函数

var dt = new Date(getDateFromIso("2012-08-03T23:00:26-05:00"));

// http://delete.me.uk/2005/03/iso8601.html
function getDateFromIso(string) {
  try{
    var aDate = new Date();
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
      offset = (Number(d[16]) * 60) + Number(d[17]);
      offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    return aDate.setTime(Number(time));
  } catch(e){
    return;
  }
}

关于google-apps-script - 如何格式化这个日期字符串以便谷歌脚本识别它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11810441/

相关文章:

javascript - 将 JSON 填充并格式化为 Google 表格

google-apps-script - Google 应用程序脚本驱动器文件 : How to get user who last modified file?

google-apps-script - 新的 Google 表格 : set text wrapping to Clip programmatically

google-apps-script - 自定义函数获取该值/Google电子表格后将值存储在单元格中

google-apps-script - 如何使用 oauth 2.0 从 appscript 到 Google API 进行授权?

google-apps-script - 有没有办法在保留文本格式的同时替换 TextBox 形状内的文本?

javascript - 在 Google Apps 脚本中获取 NWS API 500 错误

javascript - Apps 脚本 For inside For Faster

google-apps-script - 如何在 Google 文档中创建多栏页面(使用脚本)

javascript - GAS Google Script - 如何复制值并粘贴到另一个单元格中