java.time
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.
Note that the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Demo using java.time
, modern date-time API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String args[]) {
Instant instant = Instant.ofEpochMilli(0);
System.out.println(instant);
// If you need the corresponding date-time representing your timezone
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("America/New_York"));
System.out.println(zdt);
}
}
Output:
1970-01-01T00:00:00Z
1969-12-31T19:00-05:00[America/New_York]
An Instant
represents an instantaneous point on the time-line. The Z
in the output stands for Zulu which represents UTC (timezone offset of +00:00
hours).
Learn more about the the modern date-time API* from Trail: Date Time.
* 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.