title: How to convert java.util.Date to Java8 java.time.YearMonth
body: <p>How can I best convert a <code>java.util.Date</code> to a Java 8 <code>java.time.YearMonth</code>?</p>
  
  <p>Unfortunately the following throws a <code>DateTimeException</code>:</p>
  
  <pre><code>YearMonth yearMonth = YearMonth.from(date.toInstant());
  </code></pre>
  
  <p>results in:</p>
  
  <pre><code>java.time.DateTimeException: Unable to obtain YearMonth from TemporalAccessor: 2015-01-08T14:28:39.183Z of type java.time.Instant
  at java.time.YearMonth.from(YearMonth.java:264)
  ...
  </code></pre>
  
  <p>I need this functionality since I want to store <code>YearMonth</code> values in a database using JPA. Currently JPA does not support <code>YearMonth</code>'s, so I've come up with the following YearMonthConverter (imports omitted):</p>
  
  <pre><code>// TODO (future): delete when next version of JPA (i.e. Java 9?) supports YearMonth. See https://java.net/jira/browse/JPA_SPEC-63
  @Converter(autoApply = true)
  public class YearMonthConverter implements AttributeConverter&lt;YearMonth, Date&gt; {
  
    @Override
    public Date convertToDatabaseColumn(YearMonth attribute) {
      // uses default zone since in the end only dates are needed
      return attribute == null ? null : Date.from(attribute.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
  
    @Override
    public YearMonth convertToEntityAttribute(Date dbData) {
      // TODO: check if Date -&gt; YearMonth can't be done in a better way
      if (dbData == null) return null;
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(dbData);
      return YearMonth.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
    }
  }
  </code></pre>
  
  <p>Isn't there a better (cleaner, shorter) solution (for both directions)?</p>