开发者

How do you create a proper Epoch calendar object in Java?

I want to create a calendar object that is the epoch date. What's the 'correct' (if any) way to do it?

Date epochDate = new java.text.SimpleDateFormat ("dd/MM/yyyy HH:mm:ss z").parse("01/01/1970 01:00:00 GMT");
Calendar epochCal;
epochCal.setTime(epochDate);

// or maybe

Calendar ep开发者_JAVA技巧ochCal;
epochCal.setTimeInMillis(1);


The 'setTimeInMillis()' method would work fine and be easily understood by others. It might also be clearer if you passed it 0 instead of 1. The first method has more line noise and just adds more chances that something can get screwed up in maintenance.


java.time

The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat) 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 the modern API:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.EPOCH;
        System.out.println(instant);
    }
}

Output:

1970-01-01T00:00:00Z

If at all you need an object referenced by java.util.Calendar, you can get the same using this object of Instant:

// If at all you need a Calendar object, derive it from instant
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(instant.toEpochMilli());
// Verification
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println(sdf.format(calendar.getTime()));

Learn more about 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜