
package de.ivu.elect.jee.exchange;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class XmlGregorianCalendarConverter {

  private static DatatypeFactory datatypeFactory;

  static {
    try {
      datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
      throw new IllegalStateException("Exception while obtaining DatatypeFactory instance", ex);
    }
  }

  public static XMLGregorianCalendar asXMLGregorianCalendar(Date date) {
    if (date == null) {
      return null;
    }

    // einheitliches Format (UTC) (ELECTMUC-1477) => doch default verwenden ELECTMUC-1649
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setTimeInMillis(date.getTime());

    return datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);
  }

  public static Date asDate(XMLGregorianCalendar xmlGregorianCalendar) {
    if (xmlGregorianCalendar == null) {
      return null;
    }

    return xmlGregorianCalendar.toGregorianCalendar().getTime();
  }
}
