Search code examples
javadatedatetimetimezoneutc

Getting the UTC timestamp


An old Stack Overflow posting suggests that the way to get the UTC timestamp in Java is the following:

Instant.now()   // Capture the current moment in UTC.

Unfortunately, this does not work for me. I have a very simple program (reproduced below) which demonstrates different behaviour.

On Windows: the time is the local time and it is labelled with the offset with GMT

On Linux: the time is again the local time, and it is labelled correctly for the local timezone


Question: How do we display the UTC timestamp in a Java program?


My sample source code is as follows:

import java.time.Instant;
import java.util.Date;

public class UTCTimeDisplayer {
    public static void main(String[] args) {
        System.out.println(System.getProperty("os.name"));
        Date currentUtcTime = Date.from(Instant.now());
        System.out.println("Current UTC time is " + currentUtcTime);
    }
}  

Windows Output:

C:\tmp>java UTCTimeDisplayer
Windows 10
Current UTC time is Fri Jan 22 14:28:59 GMT-06:00 2021

Linux Output:

/tmp> java UTCTimeDisplayer
Linux
Current UTC time is Fri Jan 22 14:31:10 MST 2021

Solution

  • Your code:

    Date.from(Instant.now())
    

    You are mixing the terrible legacy classes with their replacement, the modern java.time classes.

    Don’t.

    Never use Date. Certainly no need to mix with java.time.Instant.

    To explain your particular example, understand that among the Date class’ many poor design choices is the anti-feature of its Date#toString method implicitly applying the JVM’s current default time zone while generating its text.

    You ran your code on two different JVMs that had different current default time zones. So you got different outputs.

    Sun, Oracle, and the JCP gave up on the legacy date-time classes. So should we all. I recommend you not spend time trying understand Date, Calendar, SimpleDateFormat, and such.

    You asked:

    Question: How do we display the UTC timestamp in a Java program?

    Instant.now().toString()
    

    See that code run live at IdeOne.com.

    2021-01-22T21:50:18.887335Z

    You said:

    On Windows: …

    On Linux: …

    You’ll get the same consistent results from Instant.now().toString() across Windows, Linux, BSD, macOS, iOS, Android, AIX, and so on.


    Here is a table I made to guide you in transitioning from the legacy classes.

    enter image description here