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
Stop using the error-prone legacy date-time API
The
java.utildate-time API and their corresponding parsing/formatting type,SimpleDateFormatare 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 tojava.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:
Output:
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.