Date formatting for XML to enable UTC offset

I am creating XML that contains a date in a valid format XML, and I need it to include an offset as well UTC.

I use groovy, but I will show the code Javathat I use (the answer in any language is good):

Calendar c = Calendar.getInstance();  
long timeZoneOffset = c.timeZone.getOffset(c.getTimeInMillis())/(1000*60*60);
SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.format(c.getTime()) + "+0" + timeZoneOffset + ":00";

The above code gives 4s me 2011-06-12T07:23:25.000+03:00, but this code has two problems:

  • This is ugly and probably not the best way to do this.
  • It will not work for time zones such as India ( GMT +5: 30 ), Nepal ( GMT +5: 45 )

I tried using new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z")for the time zone, but it gave me 2011-06-12T07:23:25.000+0300which is not the correct format ( +0300instead +03:00).

Any other way to format the date the way I need it? (preferably without third parties)

+3
source share
4 answers

Another alternative - also buried inside jaxb api - (no Jodatime required):

    Calendar c = ...
    String printDate = javax.xml.bind.DatatypeConverter.printDateTime(c);

NTN

+2
source

I think the most elegant way is to use the Joda-Time library . You need the ISO 8601 format (section 5.4) (the presented xs:dateTimeXSD type):

 DateTime dt = new DateTime();
 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
 System.out.println(fmt.print(dt));

Result:

2011-06-12T07: 36: 32,294 + 02: 00

+1
source

XMLGregorianCalendar? :

Calendar c = ...
DataTypeFactory f = DataTypeFactory.newInstance();
XMLGregorianCalendar xc = f.newXMLGregorianCalendar(c);
String str = xc.toXMLFormat();

- - , String, XML Datatypes.

0

SimpleDataFormat http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html supports the letter of the X format specifier, which includes the colon ":" in the time zone. It is worth reading the section on time zones and, in particular, on "ThreeLetterISO8601TimeZone"

Using the format string "yyyy.MM.dd HH: mm: ss.sssXXX" gave me 2015.05.07 15: 06: 58.058 + 10: 00

0
source

All Articles