Working with Dates is there a clear tutorial on how to convert UTC to Local and Local to UTC?

Trying to get my head around the best way to convert date and time from UTC to local time and visa versa.

Spending many hours trying to find a simple solution to this and I am not more confused than when I started!

Quite a simple problem.

I store dates in UTC in the database. I need to submit in local time (converted to save in UTC) and then display in local time (converted from saved UTC)

Is there a simple and clear tutorial on how to do this somewhere?

Thanks!

I don’t think there is single post for this. But this has been discussed before in the community. So best option would be to find out what solutions other people have implemented.

It requires some data about local timezone to be sent to the server side to convert between the UTC & local time.
I haven’t done it myself, but unless someone who has done it can give you direct steps, best option is to dig into other community posts talking about this.

Hey @StevenM…

I’ve worked it out. Am only on my phone at the moment so this is the outline rather than the code.

On the client side:

  1. Create a date time which is your user’s local time.

  2. Create a variable “localtime_offset” which is the number of seconds from your local time to UTC.

  3. Use the add time function to add or subtract the localtime_offset amount, depending on whether you are writing to the database or reading from it.

  4. I also store the localtime_offset value in the user table in the database for when I need to use it for example in a view.

I hope that helps… can supply code when at my computer! :slightly_smiling_face:

Best wishes,
Antony.

1 Like

HI @Antony

That’s great thank you!

Here’s some code @StevenM!

<dmx-datetime id="current_datetime" interval="seconds"></dmx-datetime>
<dmx-value id="server_offset_seconds"></dmx-value>

When my login script runs, it returns the current server time and I set the offset on the success event:

server_offset_seconds.setValue(local_datetime.datetime.secondsUntil(f_login.data.server_time))

Then I use .addSeconds() when displaying or saving times:

.addSeconds(-server_offset_seconds.value) -- when displaying a time
.addSeconds(server_offset_seconds.value)  -- when saving a time
1 Like

Here is the more rambling post where others helped me to work it out! :slight_smile:

Great stuff! Thanks, a lot clearer now!