iOS + Timezone Handling

Karthik
3 min readSep 6, 2021

--

This article is about timezones and how it has to be handled to avoid date and timezone conflicts on a different region.

Mobile apps and their development heavily rely on servers data. Where we most often have 2 variables startDate and endDate. The backend server could have stored this variable as String or Int64 (long). And here’s where the problem starts, nothing but a Timezone.

UTC (Coordinated Universal Time), a standard for setting time zones in the world. It is used to determine the time in the different zones. Time zones in the world are expressed by their +ve or -ve Offsets relative to UTC.
For eg: India is in the IST zone, i.e. UTC + 5.30, which means that if you are in India and it is 11 am (IST = UTC + 5.30), according to UTC (UTC = IST — 5.30) it is now 5.30 am.

ISSUE

we came across a situation where the backend server stored startDate and endDate in the following String format.

Obviously, mobile apps use DateFormatter API to convert the string into a date object. String to Date conversation was working fine for a region where the date was updated. But it was failing in other regions since the server timezone information (.247Z) was not matched with the current region's Timezone. Here we can see that JSONSerialization was failing due to the “Date string does not match the format expected by formatter.” We have addressed and fixed those issues using FIX 2.

# FIX 1

Timezone issues can be avoided by storing proper UTC Milliseconds (Int64 or Long) in startDate and endDate properties. but the mobile app should make sure that it always sends the proper UTC Milliseconds to the server, failing to send can pollute the server data.

# FIX 2

Before sending data to the server, mobile apps can convert the date object into a UTC string which internally strips down the timezone information. The following util can help in doing such conversation.

Sending data to the server

On the other hand, While receiving the data from the server, the date string can be converted into a proper date object by the following extension.

Conclusion

Once after the proper conversation, we can use the date object to paint our user interface by adding timezone offsets if needed.

When using dates in mobile applications, we have to be very careful when sending them to the server. In order to use time which takes the time zone into account, remember to send it in UTC format, and then convert it to your local time zone upon receipt.

That’s it for this time! 👏👏👏 . Feel free to comment if you have questions and follow to get notifications about future articles.

“Be the senior engineer you needed as a junior.” — Someone

--

--

Karthik
Karthik

No responses yet