【发布时间】: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