itsource

UTC에서 LocalDateTime을 LocalDateTime으로 변환

mycopycode 2022. 9. 3. 14:00
반응형

UTC에서 LocalDateTime을 LocalDateTime으로 변환

UTC에서 LocalDateTime을 LocalDateTime으로 변환합니다.

LocalDateTime convertToUtc(LocalDateTime date) {

    //do conversion

}

인터넷으로 검색했어요.하지만 해결책을 얻지 못했다.

저는 개인적으로

LocalDateTime.now(ZoneOffset.UTC);

가장 읽기 쉬운 옵션이기 때문입니다.

LocalDateTime에 영역 정보가 포함되어 있지 않습니다.ZonedDatetime은 그렇습니다.

LocalDateTime을 UTC로 변환하려면 ZonedDateTime 주먹으로 랩해야 합니다.

아래와 같이 변환할 수 있습니다.

LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.toLocalTime());

ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault());

ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneId.of("UTC"));

System.out.println(utcZoned.toLocalTime());

더 간단한 방법이 있다.

LocalDateTime.now(Clock.systemUTC())

질문?

정답과 문제를 보니까 문제가 많이 수정된 것 같아요.현재의 질문에 답하려면:

UTC에서 LocalDateTime을 LocalDateTime으로 변환합니다.

시간대?

LocalDateTime는 타임존에 대한 정보를 저장하지 않고 기본적으로 년, 월, 일, 시, 분, 초 및 작은 단위의 값을 저장합니다.중요한 질문은 다음과 같습니다.원본의 시간대는 어떻게 됩니까?이미 UTC일 수 있으므로 변환할 필요가 없습니다.

시스템 디폴트 타임존

질문을 한 것을 고려하면 원래 시각이 시스템 기본 시간대에 있으며 UTC로 변환해야 한다는 의미일 수 있습니다. 보통 냐 because because because because because because because becauseLocalDateTime오브젝트는 를 사용하여 생성됩니다.LocalDateTime.now()system-default의 됩니다.은 다음과

LocalDateTime convertToUtc(LocalDateTime time) {
    return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

변환 프로세스의 예를 다음에 나타냅니다.

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information

명시적 시간대

그 이외의 경우 변환하는 시간대를 명시적으로 지정하면 변환은 다음과 같습니다.

LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
    return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

변환 프로세스의 예를 다음에 나타냅니다.

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information

atZone() ★★★

atZone()메서드는 Daylight Saving Time(DST; 여름 시간)을 포함한 타임존의 모든 규칙을 고려하기 때문에 인수로서 경과된 시간에 따라 달라집니다.예에서 시간은 2월 25일이며, 유럽에서는 겨울 시간(DST 없음)을 의미합니다.

예를 들어 작년과 다른 날짜를 8월 25일로 하면 DST를 고려할 때 결과는 달라집니다.

2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information

GMT 시간은 변경되지 않습니다.따라서 다른 시간대의 오프셋이 조정됩니다.이 예에서 에스토니아 여름 시간은 GMT+3, 겨울 시간은 GMT+2입니다.

또, 클럭을 1시간 되돌리는 이행까지의 시간을 지정하는 경우도 있습니다.예: 에스토니아는 2018년 10월 28일 03:30에 두 가지 다른 시간을 의미합니다.

2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]

오프셋을 수동으로 지정하지 않고(GMT+2 또는 GMT+3) 시간은03:30타임존에 대해서Europe/Tallinn는, 2 개의 다른 UTC 시간과 2 개의 다른 오프셋을 의미합니다.

요약

보시다시피 최종 결과는 인수로 경과한 시간대에 따라 달라집니다.타임존을 추출할 수 없기 때문에LocalDateTime오브젝트를 UTC로 변환하려면 오브젝트가 어느 타임존에서 오는지를 스스로 알아야 합니다.

아래를 사용하세요.로컬 날짜/시간을 사용하고 시간대를 사용하여 UTC로 변환합니다.기능을 생성할 필요가 없습니다.

ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);
System.out.println(nowUTC.toString());

ZonedDateTime의 LocalDateTime 부분을 가져와야 할 경우 다음을 사용할 수 있습니다.

nowUTC.toLocalDateTime();

datetime 열에 기본값 UTC_TIMESTamp를 추가할 수 없기 때문에 응용 프로그램에서 UTC 시간을 mysql에 삽입하기 위해 사용하는 정적 방법을 보여 줍니다.

public static LocalDateTime getLocalDateTimeInUTC(){
    ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);

    return nowUTC.toLocalDateTime();
}

로컬 날짜 시간을 존에서 존으로 변환하기 위해 사용할 수 있는 간단한 유틸리티 클래스를 다음에 나타냅니다.이 클래스에는 로컬 날짜 시간을 현재 존에서 UTC로 직접 변환하는 유틸리티 메서드가 포함되어 있습니다(메인 메서드를 사용하여 실행하여 간단한 테스트 결과를 확인할 수 있습니다).

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {
        super();
    }

    public static void main(final String... args) {
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime utc = DateTimeUtil.toUtc(now);

        System.out.println("Now: " + now);
        System.out.println("UTC: " + utc);
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedtime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
    }

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
    }

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
    }
}

이 방법을 사용하여 시도해 보십시오.

변환하다LocalDateTime로.ZonedDateTime메서드를 사용하여 시스템 기본 시간대를 통과하거나 다음과 같이 존의 ZoneId를 사용할 수 있습니다.ZoneId.of("Australia/Sydney");

LocalDateTime convertToUtc(LocalDateTime dateTime) {
  ZonedDateTime dateTimeInMyZone = ZonedDateTime.
                                        of(dateTime, ZoneId.systemDefault());

  return dateTimeInMyZone
                  .withZoneSameInstant(ZoneOffset.UTC)
                  .toLocalDateTime();
  
}

영역 현지 날짜 시간으로 다시 변환하려면 다음을 사용합니다.

LocalDateTime convertFromUtc(LocalDateTime utcDateTime){
    return ZonedDateTime.
            of(utcDateTime, ZoneId.of("UTC"))
            .toOffsetDateTime()
            .atZoneSameInstant(ZoneId.systemDefault())
            .toLocalDateTime();
}

tldr: 그렇게 하는 방법은 없습니다.그렇게 하려고 하면 LocalDateTime이 잘못되어 버립니다.

그 이유는 인스턴스 작성 후 LocalDateTime이 타임존을 기록하지 않기 때문입니다.표준시가 없는 날짜 시간은 특정 표준시를 기준으로 다른 날짜 시간으로 변환할 수 없습니다.

실제로 LocalDateTime.now()는 랜덤한 결과를 얻는 것이 목적이 아닌 한 프로덕션 코드로 호출해서는 안 됩니다.이와 같이 LocalDateTime 인스턴스를 구성하면 이 인스턴스에는 현재 서버의 시간대에 따른 날짜 시간만 포함됩니다. 즉, 이 코드 조각이 다른 시간대 구성을 가진 서버를 실행하고 있는 경우 다른 결과를 생성합니다.

LocalDateTime은 날짜 계산을 단순화할 수 있습니다.실제로 보편적으로 사용할 수 있는 데이터 시간을 원하는 경우 ZonedDateTime 또는 OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html을 사용합니다.

다음과 같은 작업을 하는 도우미를 구현할 수 있습니다.

public static LocalDateTime convertUTCFRtoUTCZ(LocalDateTime dateTime) {
    ZoneId fr = ZoneId.of("Europe/Paris");
    ZoneId utcZ = ZoneId.of("Z");
    ZonedDateTime frZonedTime = ZonedDateTime.of(dateTime, fr);
    ZonedDateTime utcZonedTime = frZonedTime.withZoneSameInstant(utcZ);
    return utcZonedTime.toLocalDateTime();
}
public static String convertFromGmtToLocal(String gmtDtStr, String dtFormat, TimeZone lclTimeZone) throws Exception{
        if (gmtDtStr == null || gmtDtStr.trim().equals("")) return null;
        SimpleDateFormat format = new SimpleDateFormat(dtFormat);
        format.setTimeZone(getGMTTimeZone());
        Date dt = format.parse(gmtDtStr);
        format.setTimeZone(lclTimeZone);
        return

format.format(dt); }

언급URL : https://stackoverflow.com/questions/34626382/convert-localdatetime-to-localdatetime-in-utc

반응형