Saturday 25 November 2017

How to normalize dates for Android App

style="font-weight: bold;">

Answer



style="font-weight: bold;">

Answer





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.



href="https://stackoverflow.com/questions/7363112/best-way-to-work-with-dates-in-android-sqlite">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.



Answer




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.



href="http://developer.android.com/reference/java/lang/System.html#currentTimeMillis()"
rel="noreferrer">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)




href="http://developer.android.com/reference/java/util/Calendar.html#Calendar()"
rel="noreferrer">http://developer.android.com/reference/java/util/Calendar.html#Calendar()



href="http://developer.android.com/reference/java/util/Calendar.html#setTimeInMillis(long)"
rel="noreferrer">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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...