简体   繁体   English

将 JS 中的日期从一个时区转换为另一个时区

[英]Convert date in JS from one timezone to another

I want to convert a specific date string with a specific timezone to another timezone in another format.我想将具有特定时区的特定日期字符串转换为另一种格式的另一个时区。 Here is an example:这是一个例子:

var date = '2020-04-09 17:10:57'; //Date in YYYY-MM-DD HH:MM:SS format
var timezone = 'America/New_York'; //Timezone of the given var date

Now I want to convert this date in the timezone to another so for example i have:现在我想将时区中的这个日期转换为另一个日期,例如我有:

var convert_to_timezone = 'Europe/Berlin';

I just know, how to get the current users date, but I dont know, how to convert exactly this date with exactly this timezone to another.我只知道如何获取当前用户的日期,但我不知道如何将这个日期与这个时区准确地转换为另一个日期。 I also want to respect daylight saving time.我也想尊重夏令时。

The output should be: output 应该是:

//2020-04-09 23:10:57

Thanks in advance, you would really help me with an answer because I tried this 2 hours and dont get it:(在此先感谢您,您真的会帮我解答,因为我尝试了 2 个小时但没有得到它:(

Luxon is a modern re-write of Moment. Luxon 是对 Moment 的现代重写。 If you go that direction, here's working code:如果你 go 那个方向,这里的工作代码:

 var DateTime = luxon.DateTime; var date = '2020-04-09 17:10:57'; var timezone = 'America/New_York'; var format = 'yyyy-MM-dd HH:mm:ss'; var luxonTime = DateTime.fromFormat(date, format, {zone: timezone}); var berlinTime = luxonTime.setZone('Europe/Berlin').toFormat(format); console.log(berlinTime);
 <script src="https://cdn.jsdelivr.net/npm/luxon@1.23.0/build/global/luxon.min.js"></script>

On the differences between Luxon and Moment: https://github.com/moment/luxon/blob/master/docs/why.md关于Luxon和Moment的区别: https://github.com/moment/luxon/blob/master/docs/why.md

I think use moment timezone is much easier and less verbose.我认为使用时刻时区更容易且不那么冗长。

 var newYork = moment.tz("2020-04-09 17:10:57", "America/New_York"); var berlin = newYork.clone().tz("Europe/Berlin"); console.log(berlin.format())
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.28/moment-timezone-with-data.min.js"></script>

Here is an example这是一个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM