title: Java 8 Time API - ZonedDateTime - specify default ZoneId when parsing
body: <p>I am trying to write a generic method to return a <code>ZonedDateTime</code> given a date as <code>String</code> and its format. </p>
  
  <p>How do we make <code>ZonedDateTime</code> to use the default <code>ZoneId</code> if it is not specified in the date <code>String</code>? </p>
  
  <p>It can be done with <code>java.util.Calendar</code>, but I want to use the Java 8 time API.</p>
  
  <p><a href="https://stackoverflow.com/questions/27293994/how-to-parse-zoneddatetime-with-default-zone">This question here</a> is using a fixed time zone. I am specifying the format as an argument. Both the date and its format are <code>String</code> arguments. More generic. </p>
  
  <p>Code and output below: </p>
  
  <pre><code>public class DateUtil {
      /** Convert a given String to ZonedDateTime. Use default Zone in string does not have zone.  */
      public ZonedDateTime parseToZonedDateTime(String date, String dateFormat) {
          //use java.time from java 8
          DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
          ZonedDateTime zonedDateTime = ZonedDateTime.parse(date, formatter);
          return zonedDateTime;
      }
  
      public static void main(String args[]) {
          DateUtil dateUtil = new DateUtil();
          System.out.println(dateUtil.parseToZonedDateTime("2017-09-14 15:00:00+0530", "yyyy-MM-dd HH:mm:ssZ"));
          System.out.println(dateUtil.parseToZonedDateTime("2017-09-14 15:00:00", "yyyy-MM-dd HH:mm:ss"));
      }
  }
  </code></pre>
  
  <p>Output </p>
  
  <pre><code>2017-09-14T15:00+05:30
  Exception in thread "main" java.time.format.DateTimeParseException: Text '2017-09-14 15:00:00' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2017-09-14T15:00 of type java.time.format.Parsed
      at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
      at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
      at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
      at com.nam.sfmerchstorefhs.util.DateUtil.parseToZonedDateTime(DateUtil.java:81)
      at com.nam.sfmerchstorefhs.util.DateUtil.main(DateUtil.java:97)
  Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2017-09-14T15:00 of type java.time.format.Parsed
      at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
      at java.time.format.Parsed.query(Parsed.java:226)
      at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
      ... 3 more
  Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: {},ISO resolved to 2017-09-14T15:00 of type java.time.format.Parsed
      at java.time.ZoneId.from(ZoneId.java:466)
      at java.time.ZonedDateTime.from(ZonedDateTime.java:553)
      ... 5 more
  </code></pre>