Parse date with SimpleFramework

后端 未结 1 1334
攒了一身酷
攒了一身酷 2020-12-05 15:13

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

1条回答
  •  死守一世寂寞
    2020-12-05 16:13

    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
    {
        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);
    

    0 讨论(0)
提交回复
热议问题