1

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));
TtT
  • 63
  • 4
  • 1
    Did you mean to put 3 `M`s there? There should only be 2. – Sweeper Oct 05 '21 at 10:07
  • Oh... Yes, there should be 2 `M`. The problem is not with `M`. Editted. With this code I getting error: `Text '2021-10-05' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO,UTC resolved to 2021-10-05 of type java.time.format.Parsed` – TtT Oct 05 '21 at 10:14
  • Tip: Paste your exception message into your search engine. It goes much faster than waiting for an answer here. – Ole V.V. Oct 05 '21 at 12:57

2 Answers2

0

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);
Daniel
  • 807
  • 8
  • 24
0

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110