Does System.currentTimeMillis () return UTC time?

I want to get the current UTC time in milliseconds. I searched google and got some answers that System.currentTimeMillis () returns UTC time. but this is not so. If I do the following:

long t1 = System.currentTimeMillis(); long t2 = new Date().getTime(); long t3 = Calendar.getInstance().getTimeInMillis(); 

all three times are almost the same (the difference in milliseconds due to calls).

 t1 = 1372060916 t2 = 1372060917 t3 = 1372060918 

and this time is not UTC, this is the time of my time zone. How can I get the current UTC time in Android?

+64
java android datetime utc
Jun 24 '13 at 8:28
source share
2 answers

All three lines that you specify will indicate the number of milliseconds since unix, which is a fixed point in time that is independent of your local time zone.

You say that β€œthis time is not UTC” - I suspect that you were actually misdiagnosed. I would suggest using epochconverter.com . For example, in your example:

 1372060916 = Mon, 24 Jun 2013 08:01:56 GMT 

We do not know when you generated this value, but if it was not actually at 8:01 UTC, this is a problem with your system clock.

Neither System.currentTimeMillis nor the value inside Date are time zone dependent. However, you should be aware that Date.toString() uses a local time zone, which makes many developers think that Date inherently connected with the time zone - this is not the case, just in time, without an associated time zone or even calendar system.

+104
Jun 24 '13 at 8:37
source share

I can confirm that all three calls can depend on local time, given the era, not Date.toString() or any other method. I saw that they depend on local time on certain devices running Android 2.3. I have not tested them with other devices and versions of Android. In this case, the local time was set manually.

The only reliable way to get independent UTC time is to request a location update using GPS_PROVIDER . The getTime() value of the location obtained from NETWORK_PROVIDER also depends on local time. Another option is a ping server that returns a UTC timestamp, for example.

So, I do the following:

 public static String getUTCstring(Location location) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String date = sdf.format(new Date(location.getTime())); // Append the string "UTC" to the date if(!date.contains("UTC")) { date += " UTC"; } return date; } 
+1
Nov 05 '13 at 14:11
source share



All Articles