Skip to content

Instantly share code, notes, and snippets.

@ghusta
Created September 25, 2013 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghusta/6701630 to your computer and use it in GitHub Desktop.
Save ghusta/6701630 to your computer and use it in GitHub Desktop.
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