How to get my local time for a given time in different time zone in JavaScript

Viewed 693

I want to get my local time for a given time in a different time zone. I am getting the time (6/12/2020 4:23:00 PM) and the time zone (America/New_York) from the API. How to get my local time using these values.

I found the way to get the time in a different time zone.

var aestTime = new Date().toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
console.log('AEST time: '+ (new Date(aestTime)).toISOString())

But I need the other way around.

3 Answers

Luxon (the modern successor of Moment) can do this easily:

const input = '6/12/2020 4:23:00 PM';
const format = 'M/d/yyyy h:mm:ss a';
const zone = 'America/New_York';

const original = luxon.DateTime.fromFormat(input, format, { zone });
const local = original.toLocal();

console.log(local.toString()); // an ISO 8601 formatted string
console.log(local.toFormat(format)); // or whatever format you wish
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.24.1/luxon.min.js"></script>

Also, be very careful with locale-specific date formats. I'm assuming you meant M/d/yyyy as used in the USA, but in Australia they use d/M/yyyy. It would be all to easy to mix up June 12th with December 6th. You should prefer yyyy-MM-dd formatting when working with APIs.

You can use the moment library.

var moment = require('moment')

var date = moment.tz("2020-06-01T12:00:00Z", "Australia/Brisbane")
date.format()

I don't think there is a straightforward method using vanilla JS.

You could take into account the difference in offset between the runtime, given format, and UTC. Covert the date back to a UTC date and then use toLocaleString to display the date in the given format.

Roughly something like:

// create date object - this will be adjusted to utc
const localTime = new Date('6/12/2020 4:00:00 PM');
console.info('local', localTime);

// diff between local runtime and nyc - i am 3 hours behind NYC
const localOffset = -3;

// noew adjust to utc
const offset = localTime.getHours() - localTime.getUTCHours() + localOffset;

localTime.setTime(localTime.getTime() + (localOffset * (60*60*1000)));
console.info('utc', localTime);

// now you can display in locale and timezone
console.info('new york', localTime.toLocaleString("en-US", {timeZone: "America/New_York"}));

console.info('brisbane', localTime.toLocaleString("en-US", {timeZone: "Australia/Brisbane"}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment-with-locales.min.js"></script>

Related