Is there any way to convert ZoneId to ZoneOffset in java 8?

前端 未结 7 1228
礼貌的吻别
礼貌的吻别 2020-12-13 05:26

I have an epoch second and a zoneId,by method1.It can be convert to LocalDateTime with system default zoneId,but I don\'t find the way to convert epoch second to LocalDateTi

7条回答
  •  情话喂你
    2020-12-13 06:02

    I hope the first two lines of my solution below are helpful. My problem was I had a LocalDateTime and the name of a time zone, and I needed an instant so I could build a java.util.Date, because that's what MongoDB wanted. My code is Scala, but it's so close to Java here I think there should be no problem understanding it:

    val zid = ZoneId.of(tzName)                                // "America/Los_Angeles"
    val zo: ZoneOffset = zid.getRules.getOffset(localDateTime) // ⇒ -07:00
                                             // 2017-03-16T18:03
    
    val odt = OffsetDateTime.of(localDateTime, zo) // ⇒ 2017-03-16T18:03:00-07:00
    val instant = odt.toInstant                    // ⇒ 2017-03-17T01:03:00Z
    val issued = Date.from(instant)
    

提交回复
热议问题