programing

Java8 java.util.java.time으로의 날짜 변환.존 날짜 시간

projobs 2022. 9. 29. 22:18
반응형

Java8 java.util.java.time으로의 날짜 변환.존 날짜 시간

다음과 하였습니다.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.DateZonedDateTime의의날 형식 ?식? ?? ????

조다 시간까지 기다려야 하나요?

누군가 제안해 주시면 감사하겠습니다.

「」를 Instant a까지ZonedDateTime,ZonedDateTime방법을 제공합니다.그러니까

'라고 '이거'라고 하면ZonedDateTime는 「」로 할 필요가 있습니다.

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

날짜에서 ZonedDateTime을 얻으려면 다음을 사용합니다.

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

다음 '보다 낫다'라고 요.toLocalDateLocalDate가 필요한 경우 메서드를 사용합니다.다음 항목도 참조하십시오.java.util을 변환합니다.java.time 날짜로컬 날짜

아시리아에 의한 답변과 JB Nizet에 의한 답변모두 정확합니다.

  1. 레거시 클래스에 추가된 새로운 변환 메서드를 호출합니다.
  2. 를 통과하여를 호출하고, 그 결과가 됩니다.

여기에 이미지 설명 입력

하지만 당신의 암호 예는 4분의 1을 목표로 하고 있습니다.그럼, 계속 읽어봐

쿼터

25센트짜리 동전들을 마음대로 다룰 필요가 없습니다.이미 작성되고 테스트된 클래스를 사용합니다.

org.threeten.extra.YearQuarter

java.time 클래스쓰리텐 엑스트라 프로젝트에 의해 확장됩니다.그 라이브러리에서 제공되는 많은 편리한 클래스 중에서및 을 찾을 수 있습니다.

먼저, 를 입수합니다.

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

특정 날짜에 대한 연도를 결정합니다.

YearQuarter yq = YearQuarter.from( zdt ) ;

다음으로 우리는 그 분기의 시작일이 필요합니다.

LocalDate quarterStart = yq.atDay( 1 ) ;

반드시 그렇게 하는 것은 권장하지 않지만, 메서드를 구현하는 것이 아니라 한 줄의 코드를 사용할 수 있습니다.

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

덧붙여서, 만약 당신이 이 제품의 사용을 단계적으로 중단할 수 있다면java.util.Date다 같이, 그렇게 해.그것은 형제들과 함께 끔찍한 수업이다.Calendar을 사용하다Date아직 java.time으로 업데이트되지 않은 오래된 코드와 인터페이스할 때만 필요한 위치입니다.


java.time 정보

java.time 프레임워크는 Java 8 이후에 포함되어 있습니다.이러한 클래스는 , 및 등 문제가 많은 오래된 레거시 날짜 시간 클래스를 대체합니다.

자세한 내용은 Oracle 자습서를 참조하십시오.또한 Stack Overflow를 검색하여 많은 예와 설명을 확인하십시오.사양은 JSR 310입니다.

현재 유지보수 모드에 있는 조다 타임 프로젝트는 java.time 클래스로의 이행을 권장합니다.

java.time 객체를 데이터베이스와 직접 교환할 수 있습니다.JDBC 4.2 이후준거한JDBC 드라이버를 사용합니다.스트링도 필요 없고java.sql.*반.

java.time 클래스는 어디서 얻을 수 있습니까?

쓰리텐 엑스트라 프로젝트는 java.time을 추가 클래스로 확장합니다.이 프로젝트는 향후 java.time에 추가될 수 있는 가능성을 입증하는 기반입니다.여기에는 , , , 유용한 클래스가 있습니다.

Java 10 storage util에서는 답변이 통하지 않았습니다.날짜(UTC).

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

ZDT.ofInstant(instant, zoneId)와 instant.atZone(zoneId)은 순식간에 TZ에 태그가 붙는 것처럼 보이지만 이미 TZ에 태그가 붙어 있습니다.

Date.toInstant()가 UTC 시각과 시스템 시간대를 혼동하는 것을 막을 방법을 찾을 수 없었습니다.

이 문제를 해결하는 유일한 방법은 SQL을 통과하는 것이었습니다.타임스탬프 클래스:

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

반응형