Reputation: 21
I have DateTime in this format '2020-11-08T13:05:46.000-07:00'
and trying to set the same to XMLGregorianCalendar
. it gets automatically converted to 2020-11-08T20:05:46.000+0000
.
Anyway to save it as UTC?
Upvotes: 2
Views: 699
Reputation: 79620
You can do it as follows:
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String[] args) throws DatatypeConfigurationException {
String givenDateTimeString = "2020-11-08T13:05:46.000-07:00";
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(givenDateTimeString);
System.out.println(xmlGregorianCalendar);
}
}
Output:
2020-11-08T13:05:46.000-07:00
However, I suggest you switch to the modern date-time API.
Using the modern date-time API:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String givenDateTimeString = "2020-11-08T13:05:46.000-07:00";
OffsetDateTime odt = OffsetDateTime.parse(givenDateTimeString);
// Default format i.e. OffsetDateTime#toString
System.out.println(odt);
// Custom format
System.out.println(odt.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH)));
// Convert it to date-time at UTC
OffsetDateTime odtUTC = odt.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odtUTC);
System.out.println(odtUTC.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH)));
}
}
Output:
2020-11-08T13:05:46-07:00
2020-11-08T13:05:46.000-07:00
2020-11-08T20:05:46Z
2020-11-08T20:05:46.000Z
Learn more about the modern date-time API at Trail: Date Time.
Upvotes: 1
Reputation: 340188
OffsetDateTime
.parse( "2020-11-08T13:05:46.000-07:00" )
.toInstant()
XMLGregorianCalendar
is a legacy class, supplanted years ago by ZonedDateTime
.
Your input has no time zone, only an offset-from-UTC. So parse that string as an OffsetDateTime
.
OffsetDateTime odt = OffsetDateTime.parse( "2020-11-08T13:05:46.000-07:00" ) ;
Easiest way to adjust to UTC (an offset of zero hours-minutes-seconds) is to extract an Instant
.
Instant instant = odt.toInstant() ;
Upvotes: 3