Reputation: 27286
The code below:
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class FooMain {
private static final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
public static void main(String args[]) {
System.out.println(DF.format(new Date(0)));
}
}
prints out:
1970-01-01T01:00Z
Should'nt it have been 1970-01-01T00:00Z
instead? I understand that Unix Epoch time is always unambiguous and we don't have to worry about timezones, but here's my timezone in case it matters:
$ cat /etc/timezone
Europe/Madrid
Upvotes: 3
Views: 4357
Reputation: 79105
The legacy date-time API (java.util
date-time types and their formatting type, SimpleDateFormat
etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Solution using java.time
, the modern API:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
// Recommended
Instant epoch = Instant.EPOCH;
System.out.println(epoch);
// Alternatively,
epoch = Instant.ofEpochMilli(0);
System.out.println(epoch);
}
}
Output:
1970-01-01T00:00:00Z
1970-01-01T00:00:00Z
Learn more about java.time
, 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.
Upvotes: 1
Reputation: 121750
You have to .setTimeZone()
your SimpleDateFormat
; by default, the time zone is the system time zone:
final SimpleDateFormat fmt
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(fmt.format(new Date(0)));
Upvotes: 1
Reputation: 11984
new Date(0)
does correspond to January 1, 1970, 00:00:00 GMT
. The issue is that, by default, DateFormat
will print the date in your system timezone. Set the timezone on your formatter to GMT:
DF.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(DF.format(new Date(0))); // outputs: 1970-01-01T00:00Z
Upvotes: 7