1

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)?

MABC
  • 576
  • 2
  • 11
  • 29
  • You might also read this question: [Get Offset of the other Location in Javascript](https://stackoverflow.com/questions/62130983/get-offset-of-the-other-location-in-javascript). – RobG Sep 11 '20 at 00:31

2 Answers2

2

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-1

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.

gkulshrestha
  • 855
  • 1
  • 6
  • 11