dopatraman
dopatraman

Reputation: 13908

DateTimeFormatter throws DateTimeParseException for date string

The following code is throwing a DateTimeParseException:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime dt = ZonedDateTime.parse(
               "2019-01-01",
                formatter.withZone(ZoneId.of("UTC"))
        )

It also throws an exception with

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime dt = ZonedDateTime.parse(
               "2019-01-01",
                formatter)
        )

As does

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
ZonedDateTime dt = ZonedDateTime.parse(
                   "2019-01-01",
                    formatter)
            )

The SimpleDateFormat parser works just fine however -- I'm debating using it instead even though it's not thread safe and (I believe?) scheduled to be deprecated.

Obviously I'd prefer to use the java.time API, but I can't get this thing to work even after following the documented examples online. What do I do?

Upvotes: 0

Views: 1271

Answers (2)

Prasanth Rajendran
Prasanth Rajendran

Reputation: 5502

ZoneDateTime or LocalDateTime always expect pair values of date and time. If you do not have time value, but have to build ZoneDateTime or LocalDateTime instance then you can choose some default time value like '00:00' and proceed as follow:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDate.parse("2019-01-01", formatter), LocalTime.MIN, ZoneId.of("UTC"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime localDateTime = LocalDateTime.of(LocalDate.parse("2019-01-01", formatter), LocalTime.MIN);

NOTE: java.time.LocalTime has some useful time constants MIN('00:00'), MAX('23:59:59.999999999'), MIDNIGHT('00:00'), NOON('12:00')

Upvotes: 0

Jacob G.
Jacob G.

Reputation: 29680

A ZonedDateTime must contain a date and a time; your input, 2019-01-01, contains only a date.

For that reason, you should use LocalDate in conjunction with LocalDate#atTime (to get a LocalDateTime object) and LocalDateTime#atZone (with ZoneOffset.UTC to get a ZonedDateTime).


var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
var zonedDateTime = LocalDate.parse("2019-01-01", formatter)
                             .atTime(1, 2, 3) // (hours, minutes, seconds)
                             .atZone(ZoneOffset.UTC);

The value of zonedDateTime is:

2019-01-01T01:02:03Z

Upvotes: 4

Related Questions