Home > Back-end >  Java short date String convert to ZonedDateTime [duplicate]
Java short date String convert to ZonedDateTime [duplicate]

Time:10-05

I have a String with a date in this format: 2021-10-05. Need to convert this String to ZonedDateTime type. Tried to do it in this way, but the Text could not be parsed. Time can be 00:00:00. Any suggestions?

public static final ZoneId ZONE_ID = ZoneId.of("UTC");

ZonedDateTime dt2 = ZonedDateTime.parse(date, //date String = 2021-10-05
DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZONE_ID));

CodePudding user response:

You must use a LocalDate conversion first since there is no time to be parsed in the given string:

LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
ZonedDateTime dt2 = ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, ZONE_ID);

Or in a slightly more elegant way as posted in the comments:

LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
ZonedDateTime dt2 = localDate.atStartOfDay(ZONE_ID);

CodePudding user response:

The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.

Since your date string is already in ISO 8601 format, you can simply parse it into a LocalDate without needing a DateTimeFormatter and then you can use LocalDate#atStartOfDay(ZoneId) to convert the parsed value into a ZonedDateTime.

Demo:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = LocalDate.parse("2021-10-05").atStartOfDay(ZoneId.of("UTC"));
        System.out.println(zdt);
    }
}

Output:

2021-10-05T00:00Z[UTC]

ONLINE DEMO

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


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

  • Related