Search code examples
javadate-formatjava-timezoneddatetimedatetimeformatter

ZonedDateTime from date string in yyyy-mm-dd


Trying to parse a ZonedDateTime from a date string e.g '2020-08-24'.

Upon using TemporalAccesor, and DateTimeFormatter.ISO_OFFSET_DATE to parse, I am getting a java.time.format.DateTimeParseException. Am I using the wrong formatter?

Even tried adding 'Z' at the end of date string for it to be understood as UTC

private ZonedDateTime getZonedDateTime(String dateString) {
  TemporalAccessor parsed = null;
  dateString = dateString + 'Z';
  try {
     parsed = DateTimeFormatter.ISO_OFFSET_DATE.parse(dateString);
  } catch (Exception e) {
     log.error("Unable to parse date {} using formatter DateTimeFormatter.ISO_INSTANT", dateString);
  }
  return ZonedDateTime.from(parsed);
}


Solution

  • Use LocalDate#atStartOfDay

    Do it as follows:

    import java.time.LocalDate;
    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
        public static void main(String[] args) {
            // Define a DateTimeFormatter
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");
    
            // Given date string
            String strDate = "2020-08-24";
    
            // Parse the given date string to ZonedDateTime
            ZonedDateTime zdt = LocalDate.parse(strDate, dtf).atStartOfDay(ZoneOffset.UTC);
    
            System.out.println(zdt);
        }
    }
    

    Output:

    2020-08-24T00:00Z