Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to Convert type Instant to type XMLGregorianCalendar?

Tags:

java

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.

like image 650
kurb34 Avatar asked Jul 01 '15 19:07

kurb34


People also ask

How to convert String to XMLGregorianCalendar Date in java?

Usage. String input = "2014-01-07"; XMLGregorianCalendar xgc = App. getXMLGregorianCalendar( input );

How to convert Date into XMLGregorianCalendar?

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.

How to set XMLGregorianCalendar in java?

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.

What is XMLGregorianCalendar in java?

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.


1 Answers

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().

like image 177
Jesper Avatar answered Sep 25 '22 23:09

Jesper