Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DateAdapter, useful to convert String to Date and conversely, for use with JAXB 2.0. Can be used when customizing XML Schema to Java Representation Binding (XJC).
package com.developpez.hugo.ws.adapters;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* DateAdapter, useful to convert String to Date and conversely, for use with JAXB 2.0.
* <br>
* Can be used when customizing XML Schema to Java Representation Binding (XJC).
*
*/
public class JaxbDateAdapter
extends XmlAdapter<String, Date>
{
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
private static final ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<SimpleDateFormat>()
{
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat(DATE_FORMAT);
}
};
public Date unmarshal(String value)
{
if (value == null)
{
return null;
}
SimpleDateFormat sf = dateFormatter.get();
try
{
return sf.parse(value);
}
catch (ParseException e)
{
return null;
}
}
public String marshal(final Date value)
{
if (value == null)
{
return null;
}
SimpleDateFormat sf = dateFormatter.get();
return sf.format(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment