javascriptvue.jstimestamptimezonelocaltime

How to convert timestamp, depends on user timezone?


From server I'm getting timestamp like this: " 2022-12-21 16:47:10 ". And I want to convert this time to local time zone, depends on client. E.g. 16:47:10 in Poland was 10am in US. Any ideas how to achieve that? I'm using Vue framework.


Solution

  • From server I'm getting timestamp like this: "2022-12-21 16:47:10"

    That represents a date and a time without any time zone or offset. There's no way to tell that it is from Poland from this data alone.

    Thus, the first part of your solution would be to change the server-side code to do one of the following:

    For more on use cases for the options above, read DateTime vs DateTimeOffset, which was written for .NET but applies here as well.


    As far as the client-side JavaScript goes, for either of the first two options, you can pass the inputs directly to the Date object's constructor, then use methods like toString or toLocaleString. You can also use that approach for the datetime portion of the fourth option.

    For the third option though, you'll need to use a library such as Luxon to handle the input time zone identifier. The Date object cannot accept a time zone identifier as input presently. (There is a timeZone option on toLocaleString, but that is for output, not input.)

    For example:

    const dt1 = luxon.DateTime.fromISO("2022-12-21T16:47:10", {zone: "Europe/Warsaw"});
    const dt2 = dt1.toLocal();
    console.log(dt2.toString());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.1.1/luxon.min.js"></script>