我正在寻找一个函数转换日期在一个时区到另一个。

它需要两个参数,

日期(格式为“2012/04/10 10:10:30 +0000”) 时区字符串("Asia/Jakarta")

时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述

有什么简单的方法吗?


当前回答

This is UTC date; converting UTC to IST timezone; let sampleArray = [ { date: "2022-12-22T19:16:26.803" }, { date: "2022-12-22T19:16:26.77" }, { date: "2022-12-22T19:16:26.737" }, { date: "2022-12-22T19:16:26.72" } ]; // Get all the results whose boolresult is 'true' // solution 1 sampleArray.map((element) => { let utcDate = new Date(element.date).getTime(); let dateIST = new Date(utcDate); dateIST.setHours(dateIST.getHours() + 5); dateIST.setMinutes(dateIST.getMinutes() + 30); element.date = dateIST; }); console.log("Result ==>>", sampleArray); // solution 2 sampleArray.map((element) => { element.date = new Date(element.date).toLocaleString("en-US", { timeZone: "Asia/Kolkata" }); }); console.log("Result 2==>>", sampleArray);

其他回答

时区当前时区的偏移量

date +%s -d '1 Jan 1970'

对于我所在的GMT+10时区(澳大利亚),它返回-36000

你可以使用to toLocaleString()方法来设置时区。

new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

对于印度,你可以使用“印度/圣诞节”,以下是不同的时区,

"Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"

快速和肮脏的手动换时和返回:

return new Date(new Date().setHours(new Date().getHours()+3)).getHours()

我应该指出,我在可以使用的外部库方面受到了限制。moment.js和timezone-js不是我的选择。

我拥有的js日期对象是UTC。我需要在特定的时区(在我的例子中是“America/Chicago”)从这个日期获得日期和时间。

 var currentUtcTime = new Date(); // This is in UTC

 // Converts the UTC time to a locale specific format, including adjusting for timezone.
 var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));

 console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
 console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
 console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
 console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
 console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
 console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());

国际标准时间目前比“美国/芝加哥”早6小时。输出是:

currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15

currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15

我不知道一个简单的方法来转换日期对象到任何时区,但如果你想把它转换到本地时区,你可以用date .prototype. gettime()转换到相应的毫秒数,然后再回来。

let date0 = new Date('2016-05-24T13:07:20'); let date1 = new Date(date0.getTime()); console.log(“$ {date0} \ n $ {date1} ');

例如,date.getHours()现在将返回15而不是13,如果你像我一样在奥地利(而且是夏天)。

我读到过,各种datetime函数在某些浏览器中可能会表现出非标准的行为,所以先测试一下。我可以确认它在Chrome中工作。