给定的时间和偏移量;使用javascript

时间:2019-06-17 14:44:53

标签: javascript datetime timezone offset utc

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

当我尝试使用新的Date()格式时,它将转换为本地时区“ Mon Jun 17 2019 10:35:18 GMT-0400(东部夏令时间)”。 但是,如果我使用.toISOString()函数而不使用新的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;
}

实际-新日期(“ 2019-06-17 10:35:18”)。toISOString() “ 2019-06-17T14:35:18.000Z”

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

1 个答案:

答案 0 :(得分:0)

您只需将输入转换为标准格式,然后使用toISOString对象的Date函数将其转换为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"

请不要忘记时区偏移量可以是正数或负数,并且不一定总是整小时。