将Java.util日期转换为没有时区的XML日期

时间:2015-02-24 11:03:32

标签: java

我正在使用下面的代码将java util date转换为XML gregorian日历日期,但转换以某种方式将时区添加到日期。

GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(dte.getTime());
XMLGregorianCalendar xmlGrogerianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
return xmlGrogerianCalendar;

我不希望时区成为约会的一部分。任何人都可以指出我如何实现这一目标?

3 个答案:

答案 0 :(得分:11)

您可以更改时区,使其未定义。未定义的字段(在合理范围内)不会包含在输出中。

XMLGregorianCalendar xmlGrogerianCalendar =
  DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
xmlGrogerianCalendar.setTimezone( DatatypeConstants.FIELD_UNDEFINED );
return xmlGrogerianCalendar;

答案 1 :(得分:1)

您可以尝试单独设置字段

GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(System.currentTimeMillis());

try {
    XMLGregorianCalendar xmlGrogerianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();
    xmlGrogerianCalendar.setYear(gregorianCalendar.get(GregorianCalendar.YEAR));
    xmlGrogerianCalendar.setMonth(gregorianCalendar.get(GregorianCalendar.MONTH));
    xmlGrogerianCalendar.setDay(gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH));
    xmlGrogerianCalendar.setHour(gregorianCalendar.get(GregorianCalendar.HOUR_OF_DAY));
    xmlGrogerianCalendar.setMinute(gregorianCalendar.get(GregorianCalendar.MINUTE));
    xmlGrogerianCalendar.setSecond(gregorianCalendar.get(GregorianCalendar.SECOND));

    System.out.println(xmlGrogerianCalendar.toXMLFormat() );

} catch (DatatypeConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

答案 2 :(得分:0)

注意 java.util.Calendar 使用基于 0 的月份编号,而 XMLGregorianCalendar 使用基于 1。

GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(new Date().getTime());
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();
xmlGregorianCalendar.setYear(gregorianCalendar.get(GregorianCalendar.YEAR));
xmlGregorianCalendar.setMonth(gregorianCalendar.get(GregorianCalendar.MONTH) + 1);
xmlGregorianCalendar.setDay(gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH));
System.out.println(xmlGregorianCalendar);
<块引用>

2021-08-04