2017-11-30 10 views
0

다음 날짜 객체 Wed Nov 01 00:00:00 GMT 2017이 있습니다. 이것은 분명히 그리니치 표준시이지만, 다른 시간대에 있다고 생각하고 싶습니다.Java의 Date 객체에 ZoneId를 적용하십시오.

예를 들어 다음과 같은 시간대를 US/Mountain에두고이 시간을 UTC로 변환하면 Wed Nov 01 07:00:00 UTC이됩니다.

나는 시간을 유지하면서 날짜의 시간대를 변경하는 방법을 찾으려고했지만 실패했습니다.

감사

자바 시간 API와
+0

java.util.Date 또는 java.time.LocalDate를 사용합니까? – Al1

+0

java.util.Date –

+1

@AdrianDanielCulea를 사용하고 있습니다. 그런 다음 중지하십시오. 미안, 나는 저항 할 수 없었다. 진심으로, 현대 자바 날짜와 시간 API는 사용하기에 훨씬 더 좋으며, 나는 변화를 권장한다. –

답변

1

나는 당신이 java.util.Date 인스턴스를 가지고 있다고 말씀 하셨다는 점을 이해합니다. 예를 들어 Wed Nov 01 00:00:00 GMT 2017과 같이 인쇄됩니다. 이것은 그 toString 메서드가 생성하는 것입니다. Date에는 시간대가 없습니다. 일반적으로 Date.toString()은 JVM의 시간대 설정을 가져와이 시간대의 날짜를 렌더링합니다. 따라서 GMT 시간대를 실행하고있는 것으로 보입니까? this popular blog entry: All about java.util.Date에서 자세한 내용을 볼 수 있습니다.

가능한 경우 Date이 없도록하십시오. The modern Java date and time API known as java.time or JSR-310은 일반적으로나 특히 적어도 당신과 같은 시간대 마법과 관련해서는 훨씬 더 멋지게 작동합니다. 그런 다음 assylias’ answer을 사용하십시오.

이 대답을 변경하려면 변경할 수없는 (또는 지금은 변경할 수없는) 일부 레거시 API에서 Date이 있다고 가정합니다. 나는 아직도 당신이 원하는 변화를 위해 현대적인 API를 추천한다. 코드에서 주석으로 제공하는 다음 발췌 문장의 출력입니다.

System.out.println(oldFashionedDateObject); // Wed Nov 01 00:00:00 GMT 2017 
    // first thing, convert the Date to an instance of a modern class, Instant 
    Instant pointInTime = oldFashionedDateObject.toInstant(); 
    // convert to same hour and minute in US/Mountain and then back into UTC 
    ZonedDateTime convertedDateTime = pointInTime.atOffset(ZoneOffset.UTC) 
      .atZoneSimilarLocal(ZoneId.of("US/Mountain")) 
      .withZoneSameInstant(ZoneOffset.UTC); 
    System.out.println(convertedDateTime); // 2017-11-01T06:00Z 

    // only assuming you absolutely and indispensably need an old-fashioned Date object back 
    oldFashionedDateObject = Date.from(convertedDateTime.toInstant()); 
    System.out.println(oldFashionedDateObject); // Wed Nov 01 06:00:00 GMT 2017 

assylias로서, 나는 Wed Nov 01 06:00:00을 얻었다. Current Local Time in Denver, Colorado, USA에 따르면 올해 여름 (DST)은 11 월 5 일에 끝났습니다.

1

, 당신은 할 수 있습니다

  1. 는 결과를 같은

뭔가를 변환하는 ZonedDateTime

  • 사용 zonedDateTime.withZoneSameLocalzonedDateTime.withZoneSameInstant로 문자열을 구문 분석 이 :

    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu"); 
    
    ZonedDateTime gmt = ZonedDateTime.parse("Wed Nov 01 00:00:00 GMT 2017", fmt); 
    ZonedDateTime mountain = gmt.withZoneSameLocal(ZoneId.of("US/Mountain")); 
    ZonedDateTime utc = mountain.withZoneSameInstant(ZoneOffset.UTC); 
    
    System.out.println(utc.format(fmt)); 
    

    출력 : Wed Nov 01 06:00:00 Z 2017 (DST는 11 월 3 일에만 적용됩니다).

  • 관련 문제