Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to normalize dates for Android App

Tags:

android

I want to store dates in my Cloud database all under one time-zone and then for all my users (whose Android devices could be anywhere in the world), I want that date to be converted and displayed for them with whatever their default Android settings are.

Here it shows how to store dates as a long with Java in code using this: System.currentTimeMillis()

1) However, how do I "normalize" the date to be UTC (this is what I hear everyone saying I should do)?

2) Then, after that date is retrieved from the Cloud DB, how do I with Java convert that UTC date to whatever the time-zone of the device the app is installed on is?

From what I gather, Android might do some of this stuff automatically, but I am not sure what - and I am not sure what I myself have to do. Could someone clarify the above for me?

Thanks.

like image 819
Micro Avatar asked Oct 13 '15 18:10

Micro


1 Answers

According to the docs System.currentTimeMillis() returns a UTC timestamp. In other words, assuming the device has synchronized to a time server before you get the timestamp (which is very likely), it will not include a time zone adjustment.

http://developer.android.com/reference/java/lang/System.html#currentTimeMillis()

Similarly, if you retrieve the timestamp and use a Calendar object, the Calendar should adjust to the Locale of the device if you use Calendar.setTimeInMillis(long milliseconds)

http://developer.android.com/reference/java/util/Calendar.html#Calendar()

http://developer.android.com/reference/java/util/Calendar.html#setTimeInMillis(long)

In other words, you really don't have to "normalize" this information, Linux/Java does it for you. What you have to worry about is getting timestamps from email, messages or other systems that have already have a Locale adjustment, correct or not. These are the difficult timestamp problems.

like image 171
Jim Avatar answered Sep 21 '22 03:09

Jim