Parsing a string into a ZonedDateTime with UTC timezone

Edmondo1984 picture Edmondo1984 · Aug 6, 2014 · Viewed 7k times · Source

How do you parse, using using the ThreeTen library (I can't use java 8) a string of the following format:

15 Aug 2014

forcing this to become a ZonedDateTime meaning 15 August 2014 in UTC timezone at midnight?

Answer

Meno Hochschild picture Meno Hochschild · Nov 6, 2014

I assume you mean 2014, not 2010. If so then following code can help you:

LocalDate date = 
  LocalDate.parse(
    "15 Aug 2014", 
    DateTimeFormatter.ofPattern("dd MMM uuuu", Locale.ENGLISH));
ZonedDateTime zdt = date.atStartOfDay(ZoneOffset.UTC);
System.out.print(zdt);
// output: 2014-08-15T00:00Z

Another more clunky way would be to use a specialized DateTimeFormatterBuilder using the method parseDefaulting() for the missing time and offset (not tested).