developer tip

Java8 java.util.Date를 java.time.ZonedDateTime으로 변환

optionbox 2020. 12. 4. 08:07
반응형

Java8 java.util.Date를 java.time.ZonedDateTime으로 변환


로 변환 java.util.Date하는 동안 다음 예외가 발생 합니다 java.time.LocalDate.

java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2014-08-19T05:28:16.768Z of type java.time.Instant

코드는 다음과 같습니다.

public static Date getNearestQuarterStartDate(Date calculateFromDate){

    int[] quaterStartMonths={1,4,7,10};     
    Date startDate=null;

    ZonedDateTime d=ZonedDateTime.from(calculateFromDate.toInstant());
    int frmDateMonth=d.getMonth().getValue();

ZonedDateTime수업을 사용하는 방식에 문제가 있습니까?

문서에 따라 이것은 java.util.Date객체를 ZonedDateTime. 위의 날짜 형식은 표준 날짜입니까?

Joda 시간에 폴백해야합니까?

누군가가 제안을 할 수 있다면 좋을 것입니다.


를 변환하는 InstantA를 ZonedDateTime, ZonedDateTime방법을 제공합니다 ZonedDateTime.ofInstant(Instant, ZoneId). 그래서

따라서 ZonedDateTime기본 시간대 를 원한다고 가정하면 코드는

ZonedDateTime d = ZonedDateTime.ofInstant(calculateFromDate.toInstant(),
                                          ZoneId.systemDefault());

Date에서 ZonedDateTime을 얻으려면 다음을 사용할 수 있습니다.

calculateFromDate.toInstant().atZone(ZoneId.systemDefault())

그런 다음 toLocalDateLocalDate가 필요한 경우 메서드 를 호출 할 수 있습니다 . 참고 항목 : java.util.Date를 java.time.LocalDate로 변환


assylias 의해 답변JB Nizet 의해 답변은 모두 올바른 :

  1. 레거시 클래스에 추가 된 새 변환 메서드 인 java.util.Date::toInstant.
  2. 를 호출 Instant::atZone하여을 전달 ZoneId하면 ZonedDateTime.

여기에 이미지 설명 입력

그러나 코드 예제는 분기를 대상으로합니다. 그것에 대해서는 계속 읽어보십시오.

병사

분기를 직접 처리 할 필요가 없습니다. 이미 작성되고 테스트 된 클래스를 사용하십시오.

org.threeten.extra.YearQuarter

java.time의 클래스는 확장된다 ThreeTen - 추가 프로젝트. 해당 라이브러리에서 제공되는 많은 편리한 클래스 중에서 QuarterYearQuarter.

먼저 ZonedDateTime.

ZonedId z = ZoneID.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = myJavaUtilDate.toInstant().atZone( z ) ;

Determine the year-quarter for that particular date.

YearQuarter yq = YearQuarter.from( zdt ) ;

Next we need the start date of that quarter.

LocalDate quarterStart = yq.atDay( 1 ) ;

While I do not necessarily recommend doing so, you could use a single line of code rather than implement a method.

LocalDate quarterStart =                    // Represent a date-only, without time-of-day and without time zone.
    YearQuarter                             // Represent a specific quarter using the ThreeTen-Extra class `org.threeten.extra.YearQuarter`. 
    .from(                                  // Given a moment, determine its year-quarter.
        myJavaUtilDate                      // Terrible legacy class `java.util.Date` represents a moment in UTC as a count of milliseconds since the epoch of 1970-01-01T00:00:00Z. Avoid using this class if at all possible.
        .toInstant()                        // New method on old class to convert from legacy to modern. `Instant` represents a moment in UTC as a count of nanoseconds since the epoch of 1970-01-01T00:00:00Z. 
        .atZone(                            // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone). Same moment, same point on the timeline, different wall-clock time.
            ZoneID.of( "Africa/Tunis" )     // Specify a time zone using proper `Continent/Region` format. Never use 2-4 letter pseudo-zone such as `PST` or `EST` or `IST`. 
        )                                   // Returns a `ZonedDateTime` object.
    )                                       // Returns a `YearQuarter` object.
    .atDay( 1 )                             // Returns a `LocalDate` object, the first day of the quarter. 
;

By the way, if you can phase out your use of java.util.Date altogether, do so. It is a terrible class, along with its siblings such as Calendar. Use Date only where you must, when you are interfacing with old code not yet updated to java.time.


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.

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.


대답은 UTC로 util.Date를 저장하는 Java 10에서 저에게 효과적이지 않았습니다.

Date.toInstant ()는 EpochMillis를 서버의 현지 시간대로 변환하는 것 같습니다.

ZDT.ofInstant (instant, zoneId) 및 instant.atZone (zoneId)는 즉시 TZ에 태그를 지정하는 것처럼 보이지만 이미 엉망입니다.

Date.toInstant ()가 시스템 시간대의 UTC 시간을 엉망으로 만드는 것을 방지하는 방법을 찾을 수 없습니다.

이 문제를 해결하는 유일한 방법은 sql.Timestamp 클래스를 사용하는 것입니다.

new java.sql.Timestamp(date.getTime()).toLocalDateTime()
                                      .atZone(ZoneId.of("UTC"))
                                      .withZoneSameInstant(desiredTZ)

참고 URL : https://stackoverflow.com/questions/25376242/java8-java-util-date-conversion-to-java-time-zoneddatetime

반응형