javascripttimezonemomentjstimezone-offsetluxon

What is the best way to round-trip dates to Javascript in server's time zone?


I have a datetime stored in a database on a server that represents the start of a performance.

We can assume that the time zone in the location of the performance is the same as the web server and database server - that is, if it says "The performance starts at 7pm", that is necessarily and obviously local to the performance.

If I want to send that date to a web page an a response to an AJAX call and send the data back with another so that it can be edited by someone responsible for organising the event, I still want it to be local to the performance. If the performance is in Melbourne and I am setting it up in London, I don't want to have to type 9:00 into the time field because 9:00 in London is 19:00 in Melbourne. If I view a list of "performance times" in a web page, I still want it to say 19:00 whether I am in London or Melbourne; the time local to me is irrelevant.

But, if I get a JSON formatted date from my AJAX call that says /Date(1714122000000+1000)/, that is, 19:00 in Melbourne, which is correct, and turn it into a Javascript Date object, I can't NOT get it to display in the local time zone. If I add the time zone offset to the Date object so that it displays 19:00 when I am in London, then when I sent the time back to the server, it's wrong, and I have to adjust it by the offset again, which feels messy.

What is the best way to round-trip dates to the browser whilst ignoring the Browser's time zone?

I have tried: moment, luxon, native date objects. I have not tried: rolling my own date-time handling object, because I am not insane.


Solution

  • The simplest would probably be serializing the timestamp as a string without timezone information.

    Because whenever you have a a unix timestamp (ie seconds or milliseconds from 1970-01-01:00:00Z) you have unique point in time, which is the same point in time (but not necessarily the same time of the day) all over the world.

    You seem to want it the other way around: Same time of the day, regardless of your current location/timezone.

    Ie something like

    {
      ...
      date: "2024-04-26T19:00",
      ...
    }
    

    because then on the client side when this date is passed into a new Date("2024-04-26T19:00") it is interpreted according to the local timezone, ie it will always be 19:00, regardess of the timezone the browser is running in. Then you can modify the date to whatever you want.

    When you send back the date to server serialize it in the same way, ie without timezone information

    {
      ...
      "date": "2024-04-26T19:30",
      ...
    }
    

    And on the backend do the same, pass this date into a new Date("2024-04-26T19:30") and it will be interpreted in whatever timezone the backend is running in ...