MABC
MABC

Reputation: 595

Javascript translate date in a given timezone to local date

In Javascript, given a string representing a date like this one:

var dateFromPrague = "2011-10-10T14:48:00"

And knowing above date is a date from a specific localization, like Europe/Prague, how could I get this date translated to the local hour? I know I can create a Date object indicating timezone offset like this:

var dateFromPrague = new Date("2011-10-10T14:48:00.000+02:00");

Then I could get local date from above date like this:

var dateFromPragueTolocalDate = dateFromPrague.toString();

But Prague offset is not always +02:00 as it depends on DST being applied or not (summer or winter hours). So How could I indicate the right timezone, something like 'Europe/Prague', or achieve this translation some way (returning offset from server is not possible)?

Upvotes: 1

Views: 749

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

There isn't currently anything built into JavaScript itself (or the browser platform) that lets you do this, no, you're in the land of libraries. In a couple of years you'll probably be able to use Temporal, but it's still at an early stage in the proposals process. There's a polyfill linked from the proposal, but the part you'd want to use would probably be the provisionally-named LocalDateTime (not its final name) which is still a work in progress.

One library that you can do this with is Moment Timezone. That looks like this:

var a = moment.tz(dateFromPrague, "Europe/Prague");

Live Example:

var dateFromPrague = "2011-10-10T14:48:00";
var a = moment.tz(dateFromPrague, "Europe/Prague");
console.log(a.toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>

Upvotes: 2

gkulshrestha
gkulshrestha

Reputation: 885

You should get the dates in UTC from server and then you can use date.toLocaleDateString() to convert to local date. This is the typical approach.

Upvotes: -1

Related Questions