lang/java

Java Date Offset

C/H 2023. 6. 7. 13:32
package org.example;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class DatetimeOffset {
    public static void main(String[] args){
            // this simulates the parameters passed to your method
        String offset = "+07:00";
        String date = "2019-11-05 16:00";
        // provide a pattern
        String formatPattern = "yyyy-MM-dd HH:mm";
        // and create a formatter with it
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(formatPattern);
        // then parse the time to a local date using the formatter
        LocalDateTime ldt = LocalDateTime.parse(date, dtf);
        // create a moment in time at the UTC offset (that is just +00:00)
        Instant instant = Instant.ofEpochSecond(ldt.toEpochSecond(ZoneOffset.of("+00:00")));
        // and convert the time to one with the desired offset
        OffsetDateTime zdt = instant.atOffset(ZoneOffset.of(offset));
        // finally print it using your formatter
        System.out.println("UTC:\t" + ldt.format(dtf));
        System.out.println(zdt.getOffset().toString()
                + ": " + zdt.format(DateTimeFormatter.ofPattern(formatPattern)));
    }
}
> Task :DatetimeOffset.main()
UTC:	2019-11-05 16:00
+07:00: 2019-11-05 23:00
반응형

'lang > java' 카테고리의 다른 글

Java System.getenv  (0) 2023.06.08
Java Optional  (0) 2023.06.07
Java - 2 ArrayList join LinkedHapMap Filter to CSV String  (0) 2022.02.23
java filter speed Test  (0) 2021.12.31
온라인에서 자바를 배울수 있는 사이트 10가지  (0) 2014.10.06