在 JavaScript 中将日期转换为另一个时区 [英] Convert date to another timezone in JavaScript
问题描述
我正在寻找一种将一个时区中的日期转换为另一个时区的函数.
I am looking for a function to convert date in one timezone to another.
需要两个参数,
- 日期(格式为2012/04/10 10:10:30 +0000")
- 时区字符串(亚洲/雅加达")
时区字符串在 http://en.wikipedia.org/wiki/Zone 中描述.标签
有没有简单的方法可以做到这一点?
Is there an easy way to do this?
推荐答案
这里是单行:
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)
// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17
// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.
这是MDN 参考.
注意警告:上面的函数依赖于解析 toLocaleString 结果来工作,它是在 en-US
locale 中格式化的日期字符串,例如4/20/2012,下午 5:10:30"
.每个浏览器可能不接受 en-US
格式的日期字符串到它的 Date 构造函数,它可能会返回意外的结果(它可能会忽略夏令时).
Beware the caveat: function above works by relying on parsing toLocaleString result, which is string of a date formatted in en-US
locale , e.g. "4/20/2012, 5:10:30 PM"
. Each browser may not accept en-US
formatted date string to its Date constructor and it may return unexpected result (it may ignore daylight saving).
目前所有现代浏览器都接受这种格式并正确计算夏令时,它可能不适用于旧浏览器和/或异国浏览器.
Currently all modern browser accept this format and calculates daylight saving correctly, it may not work on older browser and/or exotic browser.
旁注:如果现代浏览器有 toLocaleDate 那就太好了函数,因此我们不必使用这种笨拙的方法.
side-note: It would be great if modern browser have toLocaleDate function, so we don't have to use this hacky work around.
这篇关于在 JavaScript 中将日期转换为另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!