How to set time zone of a java.util.Date?

后端 未结 10 1821
我寻月下人不归
我寻月下人不归 2020-11-22 01:45

I have parsed a java.util.Date from a String but it is setting the local time zone as the time zone of the date object.

The ti

10条回答
  •  太阳男子
    2020-11-22 02:08

    If anyone ever needs this, if you need to convert an XMLGregorianCalendar timezone to your current timezone from UTC, then all you need to do is set the timezone to 0, then call toGregorianCalendar() - it will stay the same timezone, but the Date knows how to convert it to yours, so you can get the data from there.

    XMLGregorianCalendar xmlStartTime = DatatypeFactory.newInstance()
        .newXMLGregorianCalendar(
            ((GregorianCalendar)GregorianCalendar.getInstance());
    xmlStartTime.setTimezone(0);
    GregorianCalendar startCalendar = xmlStartTime.toGregorianCalendar();
    Date startDate = startCalendar.getTime();
    XMLGregorianCalendar xmlStartTime = DatatypeFactory.newInstance()
        .newXMLGregorianCalendar(startCalendar);
    xmlStartTime.setHour(startDate.getHours());
    xmlStartTime.setDay(startDate.getDate());
    xmlStartTime.setMinute(startDate.getMinutes());
    xmlStartTime.setMonth(startDate.getMonth()+1);
    xmlStartTime.setTimezone(-startDate.getTimezoneOffset());
    xmlStartTime.setSecond(startDate.getSeconds());
    xmlStartTime.setYear(startDate.getYear() + 1900);
    System.out.println(xmlStartTime.toString());
    

    Result:

    2015-08-26T12:02:27.183Z
    2015-08-26T14:02:27.183+02:00
    

提交回复
热议问题