我正在寻找一个函数转换日期在一个时区到另一个。
它需要两个参数,
日期(格式为“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中描述
有什么简单的方法吗?
当前回答
快速和肮脏的手动换时和返回:
return new Date(new Date().setHours(new Date().getHours()+3)).getHours()
其他回答
做起来很简单:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(时区); var d = new Date(); console.log (d。toLocaleString('en-US', {timeZone}));
对于moment.js用户,现在可以使用moment-timezone。使用它,你的函数看起来像这样:
function toTimeZone(time, zone) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).tz(zone).format(format);
}
如果你有一个时区偏移,你可以使用这个:
const timezoneDate = (timestamp: number, offsetInHours: number) => {
const shiftedTimestam = timestamp + offsetInHours * 3600000;
const shiftedDate = new Date(shiftedTimestam);
return {
date: shiftedDate.getUTCDate(),
hours: shiftedDate.getUTCHours(),
minutes: shiftedDate.getUTCMinutes(),
// ...other UTC methods
}
};
// Usage:
const newYorkDate = timezoneDate(Date.now(), -5);
console.log(
`It is ${newYorkDate.hours}:${newYorkDate.minutes} in NYC`
);
你可以使用Intl。DateTimeFormat指定时区作为选项,它将日期或时间转换为所需的时区。
let timezone = "Asia/Jakarta";
let date = new Date("2012/04/10 10:10:30 +0000");
let formattedDate = new Intl.DateTimeFormat("en-US", { dateStyle: "long" , timeStyle: "short", timeZone: timezone}).format(date);
时区当前时区的偏移量
date +%s -d '1 Jan 1970'
对于我所在的GMT+10时区(澳大利亚),它返回-36000