15

I receive an XML response with an attribute which contains following value:

Wed Sep 05 10:56:13 CEST 2012

I have defined in my model class a field with annotation:

@Attribute(name = "regDate")
private Date registerDate;

However it throws an exception:

java.text.ParseException: Unparseable date: "Wed Sep 05 10:56:13 CEST 2012" (at offset 0)

Is it possible to define date format in SimpleFramework's annotations ?

What format should cover this date string ?

hsz
  • 148,279
  • 62
  • 259
  • 315
  • For new readers I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `Instant` or another class from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 04 '19 at 10:52

1 Answers1

36

SimpleXML only supports some DateFormat's:

  • yyyy-MM-dd HH:mm:ss.S z
  • yyyy-MM-dd HH:mm:ss z
  • yyyy-MM-dd z
  • yyyy-MM-dd

(For the meaning of each character see SimpleDateFormat API Doc (Java SE 7))

However it's possible to write a custom Transform who deals with other formats:

Transform

public class DateFormatTransformer implements Transform<Date>
{
    private DateFormat dateFormat;


    public DateFormatTransformer(DateFormat dateFormat)
    {
        this.dateFormat = dateFormat;
    }



    @Override
    public Date read(String value) throws Exception
    {
        return dateFormat.parse(value);
    }


    @Override
    public String write(Date value) throws Exception
    {
        return dateFormat.format(value);
    }

}

Corresponding Annotation

@Attribute(name="regDate", required=true) /* 1 */
private Date registerDate;

Note 1: required=true is optional

How to use it

// Maybe you have to correct this or use another / no Locale
DateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss z YYYY", Locale.US);


RegistryMatcher m = new RegistryMatcher();
m.bind(Date.class, new DateFormatTransformer(format));


Serializer ser = new Persister(m);
Example e = ser.read(Example.class, xml);
ollo
  • 24,797
  • 14
  • 106
  • 155
  • 1
    It seems that only `yyyy-MM-dd HH:mm:ss.S z` is supported. Tried others and exception occurs... However your solution is great and I've improved it with a cycle to support multiple formats at once without exceptions. – Davideas Jun 29 '15 at 16:11
  • Thanks for the hint (+1). – ollo Jun 30 '15 at 15:17
  • 1
    The *"how to use it"* part? That's in your code, where you want to serialize / deserialize the xml / objects. – ollo Mar 06 '16 at 17:48
  • 3
    `SimpleDateFormat` is not thread safe. Take care when sharing `dateFormat` state between threads. – Bruno Jan 25 '17 at 13:08
  • @Burno, that is true. Vote up. However, it's thread safe in Java 8. – Amr Eladawy Dec 18 '17 at 04:59