I have a Calendar instance, parsed from XSD datetime via the javax.xml.bind.DatatypeConverter.parseDateTime method by JAXB.
At runtime, i\'m in a web service, and i want
I solved my problem by using JodaTime's ISODateTimeFormat#dateTimeParser() and custom Adapter in a custom JAXB bindings file. JodaTime is much better API than the Calendar standard Java API, and it is non lenient by default.
I could have done the same for Calendar, but i should have defined all the formats myself, where JodaTime defines them already.
Here a code sample i made (it answers too to my other question: Check if xsd datetime had a defined timezone before conversion to Java object)
package com.app.adapter;
public class MyDatetimeAdapter extends XmlAdapter {
private final static DateTimeFormatter DATETIME_FORMATTER = ISODateTimeFormat.dateTime();
private final static Pattern TIMEZONE_PATTERN = Pattern.compile("(\\+|\\-)[0-9]{2}:[0-9]{2}$");
@Override
public DateTime unmarshal(String string) throws Exception {
string = string.trim();
try {
DateTime tmp = ISODateTimeFormat.dateTimeParser().parseDateTime(string);
if (string.charAt(string.length()-1) == 'Z' || TIMEZONE_PATTERN.matcher(string).find()) {
return new CustomDateTime(tmp);
}
return new CustomDateTime(tmp, CustomDateTime.Error.NO_TIMEZONE);
} catch (IllegalArgumentException e) {
return new CustomDateTime(null, CustomDateTime.Error.INVALID);
}
}
@Override
public String marshal(CustomDateTime date) throws Exception {
return DATETIME_FORMATTER.print(date.getDateTime());
}
}
And here's CustomDateTime (a POJO that wraps a JodaTime's DateTime and an error code)
package com.app.types;
public final class CustomDateTime {
private DateTime dateTime;
private Error error;
// getter .. setters .. constructor
public static CustomDateTime getInstance(Error error) {
return new CustomDateTime(DateTime.now(), error);
}
public static CustomDateTime getInstance() {
return getInstance(Error.NONE);
}
public enum Error {
NONE,
NO_TIMEZONE
INVALID;
}
}
And finally, the JAXB binding file.