【问题标题】:For a given time and offset; convert to UTC in javascript对于给定的时间和偏移量;在javascript中转换为UTC
【发布时间】:2019-06-17 14:44:53
【问题描述】:

我正在尝试将给定格式“2019-06-17 10:35:18”和偏移值“8”的时间转换为 ISO 字符串格式“2019-06-07T02:35:18.000Z”

当我尝试使用新的 Date() 格式时,它会转换为本地时区“Mon Jun 17 2019 10:35:18 GMT-0400(Eastern Daylight Time)”。 但是如果我使用 .toISOString() 函数而不使用 new Date() ,它会抛出错误。 TypeError: "2019-06-17 10:35:18".toISOString 不是函数

下面的代码是我试过的

function formatDate(date,offset){
  const year = date.getFullYear ();
  const month = date.getMonth () + 1 < 10
    ? `0${date.getMonth () + 1}`
    : date.getMonth () + 1;
  const day = date.getDate () < 10 ? `0${date.getDate ()}` : date.getDate ();
  const hour = date.getHours ().toString ().length === 1
    ? `0${date.getHours ()}`
    : date.getHours ();
  const minutes = date.getMinutes ().toString ().length === 1
    ? `0${date.getMinutes ()}`
    : date.getMinutes ();
  const seconds = date.getSeconds ().toString ().length === 1
    ? `0${date.getSeconds ()}`
    : date.getSeconds ();

  const time = `${year}/${month}/${day}T${hour-offset}:${minutes}:${seconds}.00Z`;
  return time;
}

实际 - new Date("2019-06-17 10:35:18").toISOString() “2019-06-17T14:35:18.000Z”

我想要 - 对于给定的时间和“8”的偏移量,预期结果为“2019-06-17T02:35:18.000Z”

【问题讨论】:

    标签: javascript datetime timezone offset utc


    【解决方案1】:

    您应该简单地将输入转换为标准格式,然后使用Date 对象的toISOString 函数转换为UTC。

    function formatDate(date, offset) {
        // Convert the offset number to ISO format (+/-HH:mm)
        const pad = (n) => ((n < 10 ? '0' : '') + n);
        const sign = offset < 0 ? '-' : '+';
        const offsetHours = pad(Math.abs(offset) | 0);
        const offsetMinutes = pad(Math.abs(offset) * 60 % 60);
        const offsetString = `${sign}${offsetHours}:${offsetMinutes}`;
    
        // build an ISO local time string with date and offset
        const local = `${date.slice(0,10)}T${date.slice(11)}${offsetString}`;
    
        // convert to a UTC based string and return
        return new Date(local).toISOString();
    }
    

    输入示例用法:

    formatDate('2019-06-17 10:35:18', 8)
    //=> "2019-06-17T02:35:18.000Z"
    

    不要忘记时区偏移可以是正数也可以是负数,而且并不总是以整小时为单位。

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 2012-05-01
      • 2019-07-17
      • 2011-05-01
      • 2012-06-03
      相关资源
      最近更新 更多