简体   繁体   中英

What is the best way to save epoch time in Java?

I'm using the epoch time format to save date. My problem is Java Long is enough to handle this or should I consider Java BigInteger to handle the epoch time?

Assuming you mean UNIX epoch, Java long is more then enough. UNIX epoch is number of seconds since January 1, 1970 and is stored (in UNIX) as a 32-bit int .

Yes, a long is sufficient. But in terms of the best way, consider using native types.

In Java <= 7, java.util.Date is designed for this purpose. It has millisecond precision.

In Java >= 8,java.time.Instant is designed for this purpose. It has nanosecond precision.

在 Java 中,您可以使用System.currentTimeMillis()获得自 UNIX Epoch 以来的毫秒数,它返回一个 long,因此没有理由考虑其他事情。

If by epoch time , you mean seconds since 1970, long will of course do the job, as it can represent millis as well up until end of time ;-)

My point is that you can might integer instead. it will represent time in secs since 1970 up to year 2038 .

If you don't need to represent time before now, consider using a special format like stated here . This will help you represent a wider future range.

Another option for representing time only after now, is starting the measure since 2021, by subtracting the seconds: nowSecs - 2021Secs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM