简体   繁体   中英

XMLGregorianCalendar to Date in oracle

I got XMLGregorianCalendar dates that i read from file:

<Status status="1028" timestamp="2018-03-25T01:00:00Z"/>
<Status status="1028" timestamp="2018-03-25T02:00:00Z"/>
<Status status="1028" timestamp="2018-03-25T03:00:00Z"/>

I need to store them in oracle database with the exactly same time. I got this field:

<column name="TIMESTAMP" type="DATE"/>

I got field in my entity:

@Convert(converter = XMLGregorianCalendarConverter.class)
private XMLGregorianCalendar timestamp;

and my converter:

@Converter
@Slf4j
public class XMLGregorianCalendarConverter implements AttributeConverter<XMLGregorianCalendar, Date> {

    @Override
    public Date convertToDatabaseColumn(XMLGregorianCalendar xcal) {
        return toDate(xcal);
    }

@Override
public XMLGregorianCalendar convertToEntityAttribute(Date date) {
    try {
        return toXMLGregorianCalendarWithUTCTimezone(date);
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }

    return null;
}

private DatatypeFactory getDatatypeFactory() throws DatatypeConfigurationException {
    return DatatypeFactory.newInstance();
}

private Date toDate(XMLGregorianCalendar calendar) {
    if (calendar == null) {
        return null;
    }

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

private XMLGregorianCalendar toXMLGregorianCalendarWithUTCTimezone(Date date) throws DatatypeConfigurationException {

    if (date == null) {
        return null;
    }

    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setTime(date);

    XMLGregorianCalendar xmlGregorianCalendar = getDatatypeFactory().newXMLGregorianCalendar(gregorianCalendar);
    xmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    xmlGregorianCalendar.setTimezone(DatatypeConstants.EQUAL);
    return xmlGregorianCalendar;
}

When i save them instead of getting first, second and third hour i get:

I read a lot of answers to similar questions here but i still can't make it right because i get odd results like first, third, third hour and so on.. What should i change in my converter to make it work?

Ok i resolved it by adding

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

before i return java.util.Date from toDate method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM