Java: Date from unix timestamp

后端 未结 10 1701
北荒
北荒 2020-11-22 04:10

I need to convert a unix timestamp to a date object.
I tried this:

java.util.Date time = new java.util.Date(timeStamp);

Timestamp value

10条回答
  •  梦如初夏
    2020-11-22 04:19

    java.time

    Java 8 introduced a new API for working with dates and times: the java.time package.

    With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.

    Instant instant = Instant.ofEpochSecond( timeStamp );
    

    If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.

    Date date = Date.from( instant );
    

提交回复
热议问题