Parse date with SimpleFramework

旧街凉风 提交于 2019-11-27 20:40:58

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!