Convert between LocalDate and XMLGregorianCalendar

前端 未结 4 1322
夕颜
夕颜 2020-12-08 13:05

What\'s the best way to convert between LocalDate from Java 8 and XMLGregorianCalendar?

4条回答
  •  猫巷女王i
    2020-12-08 13:40

    The following is a simple way to convert from LocalDate to XMLGregorianCalendar which both preserves the undefined fields (hours, timezone, etc.) and is efficient (i.e. no conversion to/from String). Unlike some of the other solutions this results in XML dates without timezones, e.g. 2018-11-06 instead of 2018-11-06+01:00.

    LocalDate date = ...;
    XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
    xmlCal.setYear(date.getYear());
    xmlCal.setMonth(date.getMonthValue());
    xmlCal.setDay(date.getDayOfMonth());
    

    Converting back is a bit simpler:

    XMLGregorianCalendar xmlCal = ...
    LocalDate date = LocalDate.of(xmlCal.getYear(), xmlCal.getMonth(), xmlCal.getDay());
    

提交回复
热议问题