Home > Software design >  How to convert timestamp, depends on user timezone?
How to convert timestamp, depends on user timezone?

Time:12-24

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.

CodePudding user response:

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:

  • Emit the time in terms of UTC. For example: "2022-12-21T15:47:10Z". In many cases this is the best choice, especially if your timestamps don't have any meaningful relationship to a local time zone.

  • Emit the time in terms of a local time, including the time zone offset for that point in time in that time zone. For example, if indeed the value is from Poland, then the server should emit "2022-12-21T16:47:10 01:00" because Poland is one hour ahead of UTC at that date and time.

  • Emit the time in terms of local time, but include a time zone identifier in a separate field. For example:

    {
        "datetime" : "2022-12-21T16:47:10",
        "timezone" : "Europe/Warsaw",
    }
    

    However, this approach could have ambiguities during a backward transition, such as when daylight saving time ends.

  • Combine the previous two options to resolve ambiguities:

    {
        "datetime" : "2022-12-21T16:47:10 01:00",
        "timezone" : "Europe/Warsaw",
    }
    

    This is the most complete form of the data, but generally should only be necessary if your use case is related to scheduling of future events.

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>

  • Related