我正在寻找一个函数转换日期在一个时区到另一个。
它需要两个参数,
日期(格式为“2012/04/10 10:10:30 +0000”) 时区字符串("Asia/Jakarta")
时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述
有什么简单的方法吗?
我正在寻找一个函数转换日期在一个时区到另一个。
它需要两个参数,
日期(格式为“2012/04/10 10:10:30 +0000”) 时区字符串("Asia/Jakarta")
时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述
有什么简单的方法吗?
当前回答
这对每个人都适用。您可以通过手动更改机器上的时间来测试不同的时区。这个函数将相应地进行调整。
function getCurrentTime() {
const d = new Date() //2022-07-22T16:27:21.322Z
const t = d.getTime(); //d in milliseconds 1658507241322
const offset = -d.getTimezoneOffset()/60 //current offset in hours -4
const curretMilli = t + (offset * 3600000) //cuuret local time milliseconds need to convert offset to milliseconds
return new Date(curretMilli) //converts current local time in milliseconds to a Date //2022-07-22T12:27:21.322Z
}
其他回答
使用luxon库:
import { DateTime } from "luxon";
// Convert function:
const convertTz = (datetime, fromTz, toTz, format='yyyy-MM-dd HH:mm:ss') => {
return DateTime.fromFormat(datetime, format, { zone: fromTz }).setZone(toTz).toFormat(format);
}
// Use it like this:
console.log(convertTz('2021-10-03 19:00:00', 'Europe/Lisbon', 'America/New_York'));
做起来很简单:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(时区); var d = new Date(); console.log (d。toLocaleString('en-US', {timeZone}));
有一个npm模块叫做timezones。Json你可以使用它。它基本上由一个json文件和包含夏令时和偏移量信息的对象组成。
对于asia/jakarta,它可以返回这个对象:
{
"value": "SE Asia Standard Time",
"abbr": "SAST",
"offset": 7,
"isdst": false,
"text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
"utc": [
"Antarctica/Davis",
"Asia/Bangkok",
"Asia/Hovd",
"Asia/Jakarta",
"Asia/Phnom_Penh",
"Asia/Pontianak",
"Asia/Saigon",
"Asia/Vientiane",
"Etc/GMT-7",
"Indian/Christmas"
]
}
你可以在这里找到它:
https://github.com/dmfilipenko/timezones.json
https://www.npmjs.com/package/timezones.json
希望对大家有用
如果你不想导入一些大的库,你可以使用Intl。DateTimeFormat将Date对象转换为不同的时区。
// Specifying timeZone is what causes the conversion, the rest is just formatting const options = { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: 'Asia/Jakarta', timeZoneName: 'short' } const formatter = new Intl.DateTimeFormat('sv-SE', options) const startingDate = new Date("2012/04/10 10:10:30 +0000") const dateInNewTimezone = formatter.format(startingDate) console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7
补偿,夏令时,和过去的变化将为您照顾。
更新
还有一个新的时态工具,可以处理时区和其他事情。比如只有日期或时间。目前还处于试验阶段
这是为了取代旧的遗产日期
var isoDate = new Date().toJSON() // eg: '2022-11-18T13:56:09.697Z'
Temporal.Instant.from(isoDate).toZonedDateTimeISO('Europe/Stockholm')
大多数浏览器都支持带参数的toLocaleString函数,旧的浏览器通常会忽略这些参数。
const str = new Date()。toLocaleString('en-US', {timeZone: '亚洲/雅加达'}); console.log (str);