Optional parts in SimpleDateFormat

后端 未结 7 1595
挽巷
挽巷 2020-12-09 01:09

I\'m reading in date strings that could be with or without a time zone adjustment: yyyyMMddHHmmssz or yyyyMMddHHmmss. When a string is missing a z

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 01:49

    I would create two SimpleDateFormat, one with a time zone and one without. You can look at the length of the String to determine which one to use.


    Sounds like you need a DateFormat which delegates to two different SDF.

    DateFormat df = new DateFormat() {
        static final String FORMAT1 = "yyyyMMddHHmmss";
        static final String FORMAT2 = "yyyyMMddHHmmssz";
        final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
        final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
            throw new UnsupportedOperationException();
        }
    
        @Override
        public Date parse(String source, ParsePosition pos) {
            if (source.length() - pos.getIndex() == FORMAT1.length())
                return sdf1.parse(source, pos);
            return sdf2.parse(source, pos);
        }
    };
    System.out.println(df.parse("20110102030405"));
    System.out.println(df.parse("20110102030405PST"));
    

提交回复
热议问题