Android: time stored in db is not the same as on phone

I am using System.currentTimeMillis (); to get the current time for my "modified" db field. I am converting it to unix epoch dividing it by 1000. However, even if phone / emulator date and time is set to true time, the value stored in db is 2 hours earlier than true time.

I am at GMT + 2 but cannot find how it affects.

System.currentTimeMillis () does not work; get the current time for the current time settings?

+3


source to share


3 answers


use Calendar.getInstance (), namely:

Calendar curTime = Calendar.getInstance();

      

This object curTime

will be locale specific.



From the API regarding currentTimeMillis ()

This method should not be used to measure timeouts or other measurements of elapsed time, as changing the system time may affect the results.

+2


source


currentTimeMillis

does not return time-dependent timestamps:

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC .



However, it is recommended that time stamps be stored in UTC and not include time zone offsets. To display the "correct" time, you can use SimpleDateFormat

:

SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
// set your Timezone; or use TimeZone.getDefault() for the device timezone
df.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
String time = df.format(new Date(timestamp));

      

+2


source


From the documentation:

"returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC"

This gives you the time regardless of your time zone. Therefore, you must calculate the correct time yourself.

0


source







All Articles