Xamarin Forms converting from one timezone to another

|  

Timezones Timezones - Photo by Nasa

There is a pattern here, I think. I don’t like to work with dates and you probably know that by now. Anyway, don’t like them, got to work with them. In this episode of Pains against dates, I wanted to write about something very specific that I had the pleasure to troubleshoot last week.

I have this very important and somewhat old app where all dates are saved using server local time. I don’t recommend doing that BTW. I prefer to save dates in UTC except those where the timezone is irrelevant like Production Date (fixed point in time and location). Using Xamarin, I wanted to show a date that was saved in CST in the phone’s timezone. The TimeZoneInfo class should make this easy, but timezone IDs are different between Android and iOS and I found that out the developer way: Exceptions!

If you get a TimeZoneNotFoundException chances are that the timezone id is incorrect. The timezone id used by TimeZoneInfo class is different for each device platform. Here is a subset of timezone ids for Android and iOS.

Code example that demonstrates the difference:

Fun, right?

Cheers, Lucas