Please Help Me With An Idiot's Guide to Converting UTC to Local Times

There’s several ways to do this…

One approach would be to have the user choose a timezone and store it as a preference against their record in the DB. If you store the +/- hours of the timezone, you can then use the .addHours() client-side formatter whenever displaying a date to the user.

You would always store times in UTC, as you are doing. Adjust using the user’s preference in forms - using a hidden field - if they are submitting the time to be stored.

This way if you have a user who lives in Europe, for example, but works for an American company, they could choose the timezone that suits them best.

An alternative, rather than the user having to set the timezone, would be to use something like https://ipstack.com/ to detect the user’s location when logging in - there is a timezone offset element in the API response that you could use to adjust with

You could also use a SC call to get the server time and compare it to the client’s time. If doing this, use a dynamic event when the SC that gets this this value succeeds (or on page load) to set a separate variable to the datetime value. If you just use the datetime element directly, it continues to change on every update tick so you don’t have a consistent offset against the server value that was called (and remains static). I have this method in use on a nodejs project where in the Global steps I have a servertime value set and output


and this on the page:

<body is="dmx-app" id="portalpage" dmx-on:ready="var_clientdatetime.setValue(datetime1.datetime)">
<dmx-datetime id="datetime1"></dmx-datetime>  
<dmx-value id="var_clientdatetime"></dmx-value>
  <dmx-value id="var_timeoffset" dmx-bind:value="var_clientdatetime.value.secondsUntil('<%=_('servertime',locals)%>')"></dmx-value>

The var_timeoffset value can then be used anywhere you wish and represents the second to be taken off the value to be displayed

For displaying datetime:
yourdatevalue.addSeconds(-var_timeoffset.value)
For hidden inputs if a use needs to choose a datetime and you want it converted to server time:
dmx-bind:value="yourdateinput.value.addSeconds(var_timeoffset.value)"

2 Likes