UFO ET IT

Java 8에서 ZoneId를 ZoneOffset으로 변환하는 방법이 있습니까?

ufoet 2020. 11. 29. 12:41
반응형

Java 8에서 ZoneId를 ZoneOffset으로 변환하는 방법이 있습니까?


epoch second와 zoneId, method1. 시스템 기본 zoneId를 사용하여 LocalDateTime으로 변환 할 수 있지만 method2에 의해 epoch second를 LocalDateTime으로 변환하는 방법을 찾을 수 없습니다 ZoneOffset.systemDefault.

import java.time.{Instant, LocalDateTime, ZoneId, ZoneOffset}

val epochSecond = System.currentTimeMillis() / 1000

LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.systemDefault())//method1
LocalDateTime.ofEpochSecond(epochSecond, 0, ZoneOffset.MAX)//method2

다음 ZoneOffset에서 얻을 수있는 방법은 다음과 같습니다 ZoneId.

Instant instant = Instant.now(); //can be LocalDateTime
ZoneId systemZone = ZoneId.systemDefault(); // my timezone
ZoneOffset currentOffsetForMyZone = systemZone.getRules().getOffset(instant);

주의 : ZoneId시점과 특정 장소의 역사에 따라 오프셋이 다를 수 있습니다. 따라서 다른 Instants를 선택하면 다른 오프셋이 발생합니다.


일대일 매핑이 없습니다. ZoneId는 시간이 지남에 따라 서로 다른 ZoneOffset 집합이 사용되는 지리적 범위를 정의합니다. 시간대가 일광 절약 시간제를 사용하는 경우 ZoneOffset은 여름과 겨울에 따라 다릅니다.

또한 일광 절약 시간제 규칙은 시간이 지남에 따라 변경 될 수 있으므로 ZoneOffset은 예를 들어 13/10/1980과 비교하여 2015/10/13에 대해 다를 수 있습니다.

따라서 특정 인스턴트에서만 ZoneId에 대한 ZoneOffset을 찾을 수 있습니다.

참조 https://en.wikipedia.org/wiki/Tz_database


tl; dr

ZonedDateTime.now( 
    ZoneId.of( "America/Montreal" ) 
)

… 현재 기본 시간대…

ZonedDateTime.now( 
    ZoneId.systemDefault() 
)

세부

Stanislav Bshkyrtsev 의해 답변은 정확하고 직접 질문에 응답합니다.

그러나 Jon Skeet답변 에서 제안한 것처럼 더 큰 문제가 관련되어 있습니다.

LocalDateTime

에포크 초를 LocalDateTime으로 변환하는 방법을 찾지 못했습니다.

LocalDateTime의도적으로 시간대 또는 UTC로부터의 오프셋 개념이 없습니다. 당신이 원하는 것 같지 않습니다. 특정 지역이 아닌 모든 지역을 Local…의미 합니다 . 이 클래스는 않습니다 없는 순간 만 표현 가능성이 26 ~ 27에 대한 시간 (전 세계 시간대의 범위)의 범위에 따라 순간을.

Instant

현재 시간을 얻으려는 경우 epoch 초로 시작할 필요가 없습니다. 현재 Instant. Instant클래스는 나노초 (소수점의 최대 9 자리) 의 해상도로 타임 라인의 한 순간을 UTC나타냅니다 .

Instant instant = Instant.now();

그 내부는 Instant의 수입니다 나노초 -from - 시대. 그러나 우리는 정말로 신경 쓰지 않습니다.

ZonedDateTime

특정 지역의 벽시계 시간의 렌즈를 통해 그 순간을보고 싶다면 a ZoneId적용 하여 ZonedDateTime.

ZoneId z = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = instant.atZone( z );

바로 가기로 ZonedDateTime.

ZonedDateTime zdt = ZonedDateTime.now( z );  

A ZonedDateTimeInstant내부에 있습니다. UTCzdt.toInstant() 의 기본 값과 동일한 시간을 가져 오려면 호출하십시오 . 에포크 이후로 동일한 수의 나노초, 또는 .ZonedDateTimeInstant

주어진 시대 이후 초

에포크 이후 초 수가 주어지고 에포크가 UTC ( 1970-01-01T00:00:00Z) 에서 1970 년의 첫 번째 순간 이면 그 숫자를에 입력합니다 Instant.

long secondsSinceEpoch = 1_484_063_246L ;
Instant instant = Instant.ofEpochSecond( secondsSinceEpoch ) ;

Table of date-time types in Java, both modern and legacy.


java.time 정보

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


As the documentation says, "This is primarily intended for low-level conversions rather than general application usage."

Going via Instant makes perfect sense to me - your epoch second is effectively a different representation of an Instant, so convert to an Instant and then convert that into a particular time zone.


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)

The following returns the amount of time in milliseconds to add to UTC to get standard time in this time zone:

TimeZone.getTimeZone(ZoneId.of("Europe/Amsterdam")).getRawOffset()

참고URL : https://stackoverflow.com/questions/32626733/is-there-any-way-to-convert-zoneid-to-zoneoffset-in-java-8

반응형