1var d = new Date("2020-04-13T00:00:00.000+08:00"); /* midnight in China on April 13th */
2d.toLocaleString('en-US', { timeZone: 'America/New_York' });
3//=> "4/12/2020, 12:00:00 PM"
4// (midnight in China on April 13th is noon in New York on April 12th)
1function convertTZ(date, tzString) {
2 return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
3}
4
5// usage: Asia/Jakarta is GMT+7
6convertTZ("2012/04/10 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 10 2012 17:10:30 GMT+0700 (Western Indonesia Time)
7
8// Resulting value is regular Date() object
9const convertedDate = convertTZ("2012/04/10 10:10:30 +0000", "Asia/Jakarta")
10convertedDate.getHours(); // 17
11
12// Bonus: You can also put Date object to first arg
13const date = new Date()
14convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.
1// this example takes 2 seconds to run
2const start = Date.now();
3
4console.log('starting timer...');
5// expected output: starting timer...
6
7setTimeout(() => {
8 const millis = Date.now() - start;
9
10 console.log(`seconds elapsed = ${Math.floor(millis/1000)}`);
11 // expected output : seconds elapsed = 2
12}, 2000);
13