如何使用偏移量将本地日期时间转换为 GMT

关于此问题的不同变体并不缺少问题/答案,但我似乎找不到我的场景。


如何(在 NodeJS 中)转换如下字符串;


let timeZone = "America/Chicago";

let dateTimeStr = "01-26-2020 12:34:56 PM";

具有这样的偏移量的日期时间字符串? 2020-01-26T17:34:56-05:00


这就是我正在尝试的


let timeZone = "America/Chicago";

let dateTimeString = "01-26-2020 12:34:56 PM";

newDate = new Date(dateTimeString);


console.log(`newDate=${newDate.toISOString()}`);


let dateTimeWithOffset = new Date(newDate).toLocaleString("en-US", {

  timeZone: timeZone,

  timeZoneName: "short",

});

console.log(`dateTimeWithOffset=${dateTimeWithOffset}`);

哪个产生;


newDate=2020-01-26T17:34:56.000Z

dateTimeWithOffset=2020-01-26T17:34:56.000Z

我希望在没有任何外部库的情况下做到这一点。


守候你守候我
浏览 125回答 0
0回答

ibeautiful

我知道您说过您不想使用任何外部库,但根据我的经验,处理不同的时区非常困难,特别是如果您想通过 API 或其他方式传递它们。如果您改变主意,可以使用Moment JS轻松格式化和建模字符串甚至 Date 对象中的日期// Parse timestamps using offset for provided locationvar a = moment.tz("2013-11-18 11:55", "America/Toronto");var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto");var c = moment.tz(1403454068850, "America/Toronto");console.log(  a.format() + '\n'+ // 2013-11-18T11:55:00-05:00  b.format() + '\n'+ // 2014-05-12T20:00:00-04:00  c.format()         // 2014-06-22T12:21:08-04:00);<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script><script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>您也可以更改格式moment().format();                                // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds)moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"moment().format("ddd, hA");                       // "Sun, 3PM"moment().format("[Today is] dddd");               // "Today is Sunday"moment('gibberish').format('YYYY MM DD');         // "Invalid date"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript