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 behavior.
On Windows: the time is the local time and it is labeled with the offset with GMT
On Linux: the time is again the local time, and it is labeled 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
Advertisement
Answer
The java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as “the epoch”, namely January 1, 1970, 00:00:00 GMT
(or UTC). When you print an object of java.util.Date
, its toString
method returns the date-time in the JVM’s timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat
and obtain the formatted string from it.
I would suggest you simply use Instant.now()
which you can convert to other java.time type.
The date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
However, if you still want to use java.util.Date
, use SimpleDateFormat
as mentioned above.
Demo:
import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; import java.util.TimeZone; public class Main { public static void main(String[] args) { Date currentUtcTime = Date.from(Instant.now()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); System.out.println("Current UTC time is " + sdf.format(currentUtcTime)); } }
Output:
Current UTC time is 2021-01-22 21:53:07 UTC