Many times it is best to work with UTC time when dealing with data. Especially when data may be sourced or used in multiple time zones.
I could not find any easy solution for working with time zones and UTC time. There were some extensions, but I did not want to unnecessarily add an extension. There are also some solutions using web calls, but there is no guarantee a device will have current connectivity to the Internet. Therefore, I put together a block of code to get the timezone offset.
The following block will return the device time zone offset in milliseconds. It uses the Clock component, so make sure that component is added to your project.
Below I will break down what this block is doing.
First retrieve the time zone offset using Format Date with the Pattern βZβ. βZβ will return a signed four digit number representing the time offset in using the device time retrieved from the Clock1 Now block. For example β-0430β for 4 hours and 30 minutes earlier than UTC time.
We will take to quotient of the four digit number divided by 100 to give us the hours of off set. For example -0430 will result in β-4β.
Then we canβt forget about the time zones with a half hour offset. Taking the remainder when divided by 100 will give us the minutes of off set. For example -0430 will result in β-30β
We then take the resulting minutes and divide by 60 to convert it to hours. Example -30 / 60 will result in β-0.5β.
Then add the hours and minutes together to get total offset in hours. Example -4 plus -0.5 result is β-4.5β.
Multiplying the total hours by 3600000 will convert hours to milliseconds. 60 minutes x 60 seconds x 1000 milliseconds.
Now you have the device time offset from UTC in milliseconds. For convenience, I store the result in a global variable.
Now to get UTC time, take the time and subtract the time zone offset. The following will display the current UTC time.
To convert UTC time to the device time (userβs time zone), just add the stored time to the time zone offset.
Hopefully this can help save you some time in working with UTC time. Happy koding!