My Quotes

When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go

Saturday, March 8, 2014

Date and Time Adapter for JAXB

It is often very time consuming to check for the incoming String and cast it using SimpleDateFormat in every class. Here is a simple way to fasten this by using Date Adapters in JAXB itself.

All you need to do is to define the JAXB objects to be Date as follows

@XmlElement(name = "CreditValueDate")
    private Date creditValueDate;
    @XmlElement(name = "DebitValueDate")
    private Date debitValueDate;

Class for DateTypeAdapters

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateTypeAdapter extends XmlAdapter {
    private SimpleDateFormat firstDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat secondDateFormat = new SimpleDateFormat("yyyy/MM/dd");

    public String marshal(Date v) {
 return secondDateFormat.format(v);

    public Date unmarshal(String v) throws ParseException {
 Date returnDate = null;
 try {
     returnDate = firstDateFormat.parse(v);
 } catch (Exception prse) {
     returnDate = secondDateFormat.parse(v);
 return returnDate;

No comments :