How can I convert a time in milliseconds to ZonedDateTime

前端 未结 4 600
忘了有多久
忘了有多久 2021-01-13 03:18

I have the time in milliseconds and I need to convert it to a ZonedDateTime object.

I have the following code

long m = System.currentTimeMillis();
L         


        
4条回答
  •  春和景丽
    2021-01-13 03:58

    Whether you want a ZonedDateTime, LocalDateTime, OffsetDateTime, or LocalDate, the syntax is really the same, and all revolves around applying the milliseconds to an Instant first using Instant.ofEpochMilli(m).

    long m = System.currentTimeMillis();
    
    ZonedDateTime  zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
    LocalDateTime  ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
    OffsetDateTime odt = OffsetDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
    LocalDate      ld  = LocalDate.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
    

    Printing them would produce something like this:

    2018-08-21T12:47:11.991-04:00[America/New_York]
    2018-08-21T12:47:11.991
    2018-08-21T12:47:11.991-04:00
    2018-08-21
    

    Printing the Instant itself would produce:

    2018-08-21T16:47:11.991Z
    

提交回复
热议问题