javadatetimesimpledateformatlocaltime

Convert Date to UTC DateTime


I have the date 2023-04-03 and wanted to convert it into UTC time with range (start and end of the day)

2023-04-03T00:00:00 -> 2023-04-02T18:30:00z
2023-04-03T24:00:00 -> 2023-04-03T18:30:00z

Input: 2023-04-03
Need this output: 2023-04-02T06:30:00z, 2023-04-03T18:30:00z

I have tried LocalDate and SimpleDateFormatter, but they are not converting to this way.

LocalDateTime ldt = LocalDate.parse("2023-04-03").atStartOfDay();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("UTC"));
Instant instant = zdt.toInstant();
System.out.println(":inst: " + instant.toString());

output of the above code:

Hello: 2016-06-12T00:00

:inst: 2016-06-12T00:00:00Z


Solution

  • I have tried LocalDate and SimpleDateFormatter, but they are not converting to this way.

    Stop using the error-prone legacy date-time API

    The java.util date-time API and their corresponding parsing/formatting type, SimpleDateFormat are outdated and error-prone. In March 2014, the modern Date-Time API was released as part of the Java 8 standard library which supplanted the legacy date-time API and since then it is strongly recommended to switch to java.time, the modern date-time API.

    You need a time zone to get the desired output

    Your desired output (start and end of the day) is in UTC and therefore you need to convert the date-time from your time zone to UTC. Once you have start and end of the day in your time zone, you can convert them to UTC using ZonedDateTime#withZoneSameInstant.

    Demo:

    class Main {
        public static void main(String[] args) {
            ZoneId zoneIndia = ZoneId.of("Asia/Kolkata");
            LocalDate date = LocalDate.parse("2023-04-03");
    
            System.out.println(date.atStartOfDay(zoneIndia)
                    .withZoneSameInstant(ZoneOffset.UTC));
    
            System.out.println(date.atStartOfDay(zoneIndia).with(LocalTime.MAX)
                    .withZoneSameInstant(ZoneOffset.UTC));
    
            // Or get the exlusive upper range (half-open interval for the day)
            System.out.println(date.plusDays(1).atStartOfDay(zoneIndia)
                    .withZoneSameInstant(ZoneOffset.UTC));
        }
    }
    

    Output:

    2023-04-02T18:30Z
    2023-04-03T18:29:59.999999999Z
    2023-04-03T18:30Z
    

    ONLINE DEMO

    Learn more about the modern Date-Time API from Trail: Date Time.