Pythogen
Pythogen

Reputation: 640

System.currentTimeMillis() and daylight savings

I am wondering if System.currentTimeMillis() accounts for daylight savings on android.

Let's say I call x = System.currentTimeMillis();

and then ten seconds later, the os switches the clock back an hour because of daylight savings.

And now I call y = System.currentTimeMillis();

Which will be larger, x or y?

I ask this because if I manually change the clock, x is greater than y. So I wonder if daylight savings is accounted for when calculating the long value returned by System.currentTimeMillis(). Can't seem to find anything in the docs.

Upvotes: 7

Views: 2322

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339382

No, DST has no effect

if System.currentTimeMillis() accounts for daylight savings

No.

Daylight Saving Time (DST) is irrelevant to System.currentTimeMillis.

The call to System.currentTimeMillis gives you a number of milliseconds since the first moment of 1970 in UTC, 1970-01-01T00:00:00Z. No adjustments for Leap Second.

DST is defined, and redefined, on the whim of bored/uneducated/crazy politicians. DST applies only to their jurisdiction in one or more particular time zones.

DST cutovers are anomalies, disrupting wall-clock time for a region’s citizens. But space-time does not bend or warp with a DST cutover, time continues to flow smoothly. That flow of time is measured by System.currentTimeMillis without regard to machinations of local politicians.

Instant

The System.currentTimeMillis() method is now obsolete. To get the current moment, use java.time.Instant.now.

Instant now = Instant.now() ;

While a Instant can hold nanoseconds, in Java 9 and later you are likely to see the current moment captured in microseconds. (Java 8 used milliseconds, before a new implementation of Clock in Java 9 and later.)

In contrast, the System.currentTimeMillis call is limited to milliseconds.

To get a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z, call Instant::toEpochMilli. Of course, beware of data loss as any microseconds or nanoseconds are truncated from the result as milliseconds.

long millisecondsSinceEpoch = Instant.now().toEpochMilli() ;

Instant represents a moment in UTC. So Daylight Saving Time (DST) and similar anomalies caused by politicians have no effect.

Upvotes: 10

Related Questions