bewikec973
bewikec973

Reputation: 13

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:

//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 :(

Upvotes: 1

Views: 327

Answers (2)

WillD
WillD

Reputation: 6512

Luxon is a modern re-write of Moment. If you go that direction, here's working code:

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/[email protected]/build/global/luxon.min.js"></script>

On the differences between Luxon and Moment: https://github.com/moment/luxon/blob/master/docs/why.md

Upvotes: 3

Andy Song
Andy Song

Reputation: 4684

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

Upvotes: 1

Related Questions