IT

Instant와 LocalDateTime의 차이점은 무엇입니까?

lottoking 2020. 5. 12. 08:10
반응형

Instant와 LocalDateTime의 차이점은 무엇입니까?


나는 그것을 알고있다 :

  • Instant 는 오히려 컴퓨팅을위한 "기술적 인"타임 스탬프 표현 (나노초)입니다.
  • LocalDateTime 은 사람을위한 시간대를 포함한 날짜 / 시계입니다.

여전히 최종 IMO에서는 둘 다 대부분의 응용 프로그램 사용 사례의 유형으로 사용할 수 있습니다. 예를 들어 : 현재 날짜를 기준으로 다음 실행을 계산 해야하는 배치 작업을 실행 중이며 인스턴트와 시간대 부분의 나노 초 정밀도 이점을 제외 하고는이 두 유형 사이의 장단점을 찾는 데 어려움을 겪고 있습니다. LocalDateTime).

Instant 또는 LocalDateTime 만 사용해야하는 일부 응용 프로그램의 이름을 지정할 수 있습니까?

편집 : 정밀도 및 시간대와 관련하여 LocalDateTime에 대한 잘못된 문서를주의하십시오


최신 java.time 대 레거시의 날짜-시간 클래스 유형 표

tl; dr

Instant그리고 LocalDateTime두 개의 완전히 다른 동물이다 : 하나는 순간을 나타내고, 다른 하나는하지 않습니다.

  • Instant 타임 라인의 특정 지점 인 순간을 나타냅니다.
  • LocalDateTime날짜와 시간을 나타냅니다. 그러나 표준 시간대 나 UTC에서 오프셋 없으면 이 클래스 순간을 나타낼 수 없습니다 . 그것은 세계의 모든 시간대의 범위 인 약 26-27 시간 범위의 잠재적 인 순간을 나타냅니다 .

잘못된 추정

LocalDateTime 인간을위한 시간대를 포함하여 오히려 날짜 / 시계 표현입니다.

귀하의 진술이 잘못되었습니다 : A 표준 시간대 LocalDateTime없습니다 . 시간대가없는 것이 그 수업의 핵심입니다.

해당 클래스의 doc을 인용하려면 :

이 클래스는 시간대를 저장하거나 나타내지 않습니다. 대신, 생일에 사용되는 벽시계에서 볼 수있는 현지 시간과 함께 날짜에 대한 설명입니다. 오프셋 또는 시간대와 같은 추가 정보가 없으면 타임 라인에서 순간을 나타낼 수 없습니다.

따라서 Local…"구역화되지 않음, 오프셋 없음"을 의미합니다.

Instant

여기에 이미지 설명을 입력하십시오

Instant의 타임 라인에 순간 UTC 의 카운트 나노초 1970 UTC (기본적으로, 핵심적 견실 한 세부 사항에 대한 클래스 문서를 참조)의 첫 순간의 시대입니다. 대부분의 비즈니스 로직, 데이터 스토리지 및 데이터 교환은 UTC로 이루어져야하므로 자주 사용하는 편리한 클래스입니다.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

OffsetDateTime

클래스 OffsetDateTime클래스는 UTC보다 앞 또는 뒤에서 몇 분 분 단위의 컨텍스트로 날짜와 시간으로 순간을 나타냅니다. 오프셋은 시간-분-초 수로 ZoneOffset클래스에 의해 표시됩니다 .

시-분-초 수가 0 인 경우 OffsetDateTime는 UTC와 모멘트를 나타냅니다 Instant.

ZoneOffset

ZoneOffset클래스는 UTC 보다 앞뒤 또는 UTC보다 몇 시간 분 단위 로 UTC에서 오프셋을 나타냅니다 .

A ZoneOffset는 단지 몇 시간 분만에 지나지 않습니다. 이름과 오프셋 변경 내역이있는 영역이 훨씬 더 많습니다. 따라서 단순한 오프셋을 사용하는 것보다 항상 영역을 사용하는 것이 좋습니다.

ZoneId

여기에 이미지 설명을 입력하십시오

시간대 에 의해 표현되는 ZoneId클래스입니다.

예를 들어 몬트리올 보다 파리 에서 새로운 하루 가 시작됩니다 . 따라서 주어진 지역에 대해 정오 (태양이 직접 오버 헤드 인 경우) 를 더 잘 반영하려면 시계 바늘을 움직여야합니다 . 서유럽 / 아프리카의 UTC 라인에서 동쪽 / 서쪽으로 멀수록 오프셋이 더 커집니다.

표준 시간대는 지역 사회 또는 지역에서 실시하는 조정 및 예외 사항을 처리하기위한 일련의 규칙입니다. 가장 일반적인 예외는 일광 절약 시간 (DST) 으로 알려진 너무나 대중적인 미치 입니다.

시간대에는 과거 규칙, 현재 규칙 및 가까운 미래에 대해 확인 된 규칙의 기록이 있습니다.

이러한 규칙은 예상보다 자주 변경됩니다. 날짜-시간 라이브러리의 규칙, 일반적으로 'tz'데이터베이스 사본을 최신 상태로 유지하십시오 . Oracle이 Timezone Updater Tool을 출시함으로써 Java 8에서 최신 상태를 유지하는 것이 그 어느 때보 다 쉬워졌습니다 .

지정 적절한 시간대 이름 의 형식 Continent/Region예컨대, America/Montreal, Africa/Casablanca, 또는 Pacific/Auckland. 표준 시간대 아니EST 거나 표준화되지 않았으며 고유하지 않은 2-4 자로 된 약어는 사용하지 마십시오 .IST

시간대 = 오프셋 + 조정 규칙

ZoneId z = ZoneId.of( “Africa/Tunis” ) ; 

ZonedDateTime

여기에 이미지 설명을 입력하십시오

ZonedDateTime개념적으로 Instant할당 된 으로 생각하십시오 ZoneId.

ZonedDateTime = (인스턴트 + ZoneId)

특정 지역 (시간대)의 사람들이 사용하는 벽시계 시간에서 볼 수있는 현재 순간을 포착하려면 :

ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Pass a `ZoneId` object such as `ZoneId.of( "Europe/Paris" )`. 

거의 모든 백엔드, 데이터베이스, 비즈니스 로직, 데이터 지속성, 데이터 교환은 모두 UTC로 이루어져야합니다. 그러나 사용자에게 표시하려면 사용자가 예상 한 시간대로 조정해야합니다. 이것은 ZonedDateTime클래스와 그 날짜-시간 값의 문자열 표현을 생성하는 데 사용되는 포맷터 클래스 의 목적입니다 .

ZonedDateTime zdt = instant.atZone( z ) ;
String output = zdt.toString() ;                 // Standard ISO 8601 format.

을 사용하여 현지화 된 형식으로 텍스트를 생성 할 수 있습니다 DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ; 
String outputFormatted = zdt.format( f ) ;

mardi 30 avril 2019 à 23 시간 22 분 55 s heure de l' Inde

LocalDate, LocalTime,LocalDateTime

<code> LocalDate </ code>의 달력 만 표시하는 다이어그램.

<code> LocalTime </ code>의 시계 만 보여주는 다이어그램.

<code> LocalDateTime </ code>의 달력과 시계를 보여주는 다이어그램.

"로컬"날짜 시간 클래스는, LocalDateTime, LocalDate, LocalTime, 생물의 다른 종류입니다. 지역이나 시간대와 관련이 없습니다. 타임 라인에 묶여 있지 않습니다. 타임 라인에서 요점을 찾기 위해 지역에 적용하기 전까지 는 의미가 없습니다 .

이 클래스 이름에서 "로컬"이라는 단어는 시작하지 않은 사람에게는 반 직관적 일 수 있습니다. 단어는 모든 지역 또는 모든 지역을 의미 하지만 특정 지역은 아닙니다 .

따라서 비즈니스 앱의 경우 "로컬"유형은 타임 라인의 특정 순간이 아닌 가능한 날짜 또는 시간에 대한 일반적인 아이디어를 나타 내기 때문에 자주 사용되지 않습니다. 비즈니스 앱은 송장이 도착한 순간, 운송을 위해 선적 된 제품, 직원을 고용했거나 택시가 차고를 떠난 순간을 중요하게 생각합니다. 비즈니스 응용 프로그램 개발자의 사용 그래서 InstantZonedDateTime가장 일반적으로 클래스.

그럼 언제 사용 LocalDateTime할까요? 세 가지 상황 : 여러 위치에 걸쳐 특정 날짜 및 시간을 적용하려는 경우, 약속을 예약하는 경우 또는 아직 결정되지 않은 표준 시간대가있는 경우. 이 세 가지 사례 중 어느 것도 타임 라인의 특정 특정 지점이 아니며 순간도 아닙니다.

하루에 한 번, 여러 순간

때로는 특정 날짜의 특정 시간을 나타내려고하지만 시간대의 여러 지역에 적용하려고합니다.

예를 들어 "크리스마스는 2015 년 12 월 25 일 자정에 시작합니다"는입니다 LocalDateTime. 자정은 파리에서 몬트리올과는 다른 순간에, 그리고 시애틀오클랜드 에서 또 다른 순간 칩니다 .

LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ;   // 00:00:00
LocalTime ldt = LocalDateTime.of( ld , lt ) ;  // Xmas morning anywhere. 

또 다른 예로 "Acme Company는 전 세계 각 공장에서 점심 시간이 오후 12:30에 시작한다는 정책을 가지고 있습니다"입니다 LocalTime. 진정한 의미를 가지려면 슈투트가르트 공장에서 12:30, 라바트 공장에서 12:30, 시드니 공장 에서 12:30의 순간을 파악하기 위해 타임 라인에 적용해야합니다 .

예약 약속

Another situation to use LocalDateTime is for booking future events (ex: Dentist appointments). These appointments may be far enough out in the future that you risk politicians redefining the time zone. Politicians often give little forewarning, or even no warning at all. If you mean "3 PM next January 23rd" regardless of how the politicians may play with the clock, then you cannot record a moment – that would see 3 PM turn into 2 PM or 4 PM if that region adopted or dropped Daylight Saving Time, for example.

For appointments, store a LocalDateTime and a ZoneId, kept separately. Later, when generating a schedule, on-the-fly determine a moment by calling LocalDateTime::atZone( ZoneId ) to generate a ZonedDateTime object.

ZonedDateTime zdt = ldt.atZone( z ) ;  // Given a date, a time-of-day, and a time zone, determine a moment, a point on the timeline.

If needed, you can adjust to UTC. Extract an Instant from the ZonedDateTime.

Instant instant = zdt.toInstant() ;  // Adjust from some zone to UTC. Same moment, same point on the timeline, different wall-clock time.

Unknown zone

Some people might use LocalDateTime in a situation where the time zone or offset is unknown.

I consider this case inappropriate and unwise. If a zone or offset is intended but undetermined, you have bad data. That would be like storing a price of a product without knowing the intended currency. Not a good idea.

All date-time types

For completeness, here is a table of all the possible date-time types, both modern and legacy in Java, as well as those defined by the SQL standard. This might help to place the Instant & LocalDateTime classes in a larger context.

SQL 표준뿐만 아니라 Java (현대 및 레거시)의 모든 날짜-시간 유형 표.

Notice the odd choices made by the Java team in designing JDBC 4.2. They chose to support all the java.time times… except for the two most commonly used classes: Instant & ZonedDateTime.

But not to worry. We can easily convert back and forth.

Converting Instant.

// Storing
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;

// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;

Converting ZonedDateTime.

// Storing
OffsetDateTime odt = zdt.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;

// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZone( z ) ; 

About 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.

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

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

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.


One main difference is the Local part of LocalDateTime. If you live in Germany and create a LocalDateTime instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant, which is calculated independently from time zone.

LocalDateTime stores date and time without timezone, but it's initial value is timezone dependent. Instant's is not.

Moreover, LocalDateTime provides methods for manipulating date components like days, hours, months. An Instant does not.

apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime

Both classes have the same precision. LocalDateTime does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.


You are wrong about LocalDateTime: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

The difference between the two is that Instant represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant objects created at the same moment in two different places of the Earth will have exactly the same value.


Instant corresponds to time on the prime meridian (Greenwich).

Whereas LocalDateTime relative to OS time zone settings, and

오프셋 또는 시간대와 같은 추가 정보가 없으면 순간을 나타낼 수 없습니다.

참고 URL : https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime

반응형