Code:
private static Instant now;
now = new Instant();
How do I convert the variable now to type XMLGregorianCalendar? I've been doing research on it and I'm quite confused. I have found no similar questions, and so anything will be useful.
Note: I am using Java 6.
Usage. String input = "2014-01-07"; XMLGregorianCalendar xgc = App. getXMLGregorianCalendar( input );
The simplest way to format XMLGregorianCalendar is to first convert it to the Date object, and format the Date to String. XMLGregorianCalendar xCal = ..; //Create instance Date date = xCal. toGregorianCalendar(). getTime(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a z"); String formattedString = df.
In this approach, we have first changed the standard date to Gregorian Calendar date format and then changed it to XML Gregorian Date using the DatatypeFactory(). newInstance method which creates new javax. xml. datatype Objects that map XML to/from Java Objects.
public abstract class XMLGregorianCalendar extends Object implements Cloneable. Representation for W3C XML Schema 1.0 date/time datatypes. Specifically, these date/time datatypes are DatatypeConstants. DATETIME , DatatypeConstants. TIME , DatatypeConstants.
You can do it like this:
Instant now = Instant.now();
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTimeInMillis(now.toEpochMilli());
XMLGregorianCalendar cal2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal1);
If you are doing this just because you want to format an Instant
to a String
in ISO 8601 format, then there is an easier way:
String dateTime = DateTimeFormatter.ISO_INSTANT.format(now);
edit - for the Joda Time class Instant
, do now.getMillis()
instead of now.toEpochMilli()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With