The Open Event Android project helps event organizers to organize the event and generate Apps (apk format) for their events/conferences by providing API endpoint or zip generated using Open Event server. For any Event App it is very important that it handles time zone properly. In Open Event Android App there is an option to change time zone setting. The user can view date and time of the event and sessions in Event Timezone and Local time zone in the App. ThreeTenABP provides a backport of the Java SE 8 date-time classes to Java SE 6 and 7. In this blog post I explain how to use ThreeTenABP for time zone handling in Android.
To use ThreeTenABP in your application you have to add the dependency in your app module’s build.gradle file.
Now in the onCreate() method of the Application class initialize ThreeTenABP.
Create getZoneId() method
Firstly create getZoneId() method which will return ZoneId according to user preference. This method will be used for formatting and parsing dates Here showLocal is user preference. If showLocal is true then this function will return Default local ZoneId otherwise ZoneId of the Event.
Here getEventTimeZone() method returns time zone string of the Event.
ThreeTenABP has mainly two classes representing date and time both.
- ZonedDateTime : ‘2011-12-03T10:15:30+01:00[Europe/Paris]’
- LocalDateTime : ‘2011-12-03T10:15:30’
ZonedDateTime contains timezone information at the end. LocalDateTime doesn’t contain timezone.
Create method for parsing and formating
Now create getDate() method which will take isoDateString and will return ZonedDateTime object.
Create formatDate() method which takes two arguments first is format string and second is isoDateString. This method will return a formatted string.
Now we are ready to format and parse isoDateString. Let’s take an example. Let “2017-11-09T23:08:56+08:00” is isoDateString. We can parse this isoDateString using getDate() method which will return ZonedDateTime object.
As you can see, ThreeTenABP makes Time Zone handling so easy. It has also support for default formatters and methods. To learn more about ThreeTenABP follow the links given below.
- Github repo: https://github.com/JakeWharton/ThreeTenABP
- DateTime formatting tutorial by Jakob Jenkov: http://tutorials.jenkov.com/java-date-time/datetimeformatter.html
- Open Event Android PR: https://github.com/fossasia/open-event-android/pull/1879