Android parse String to Date - unknown pattern character 'X'

前端 未结 13 1010
耶瑟儿~
耶瑟儿~ 2021-01-31 07:32

I have Service fetch date string from web and then I want to pare it to Date object. But somehow application crashes. This is my string that I\'m parsi

13条回答
  •  日久生厌
    2021-01-31 07:50

    Based on idea from Alexander K, I optimize it and support parsing from and to UTC timezone format like 1970-01-01T00:00:00Z, to make all behaviour exactly same as yyyy-MM-dd'T'HH:mm:ssXXX.

    public class IsoSimpleDateFormatBeforeNougat extends SimpleDateFormat {
    
        public IsoSimpleDateFormatBeforeNougat() {
            super("yyyy-MM-dd'T'HH:mm:ssZ");
        }
    
        public IsoSimpleDateFormatBeforeNougat(Locale locale) {
            super("yyyy-MM-dd'T'HH:mm:ssZ", locale);
        }
    
        public IsoSimpleDateFormatBeforeNougat(DateFormatSymbols formatSymbols) {
            super("yyyy-MM-dd'T'HH:mm:ssZ", formatSymbols);
        }
    
        @Override
        public Date parse(String text, ParsePosition pos) {
            if (text.endsWith("Z")) {
                return super.parse(text.substring(0, text.length() - 1) + "+0000", pos);
            }
            if (text.length() > 3 && text.substring(text.length() - 3, text.length() - 2).equals(":")) {
                text = text.substring(0, text.length() - 3) + text.substring(text.length() - 2);
            }
            return super.parse(text, pos);
        }
    
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
            StringBuffer rfcFormat = super.format(date, toAppendTo, pos);
            if (rfcFormat.substring(rfcFormat.length() - 5).equals("+0000")) {
                return rfcFormat.replace(rfcFormat.length() - 5, rfcFormat.length(), "Z");
            }
            return rfcFormat.insert(rfcFormat.length() - 2, ":");
        }
    }
    

    Test code:

    @Test
    public void test() throws ParseException {
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        SimpleDateFormat sdf = new IsoSimpleDateFormatBeforeNougat();
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    
        assertEquals("1970-01-01T08:00:00+08:00", sdf.format(new Date(0)));
        assertEquals(0L, sdf.parse("1970-01-01T08:00:00+08:00").getTime());
    
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    
        assertEquals("1970-01-01T00:00:00Z", sdf.format(new Date(0)));
        assertEquals(0L, sdf.parse("1970-01-01T00:00:00Z").getTime());
    }
    

提交回复
热议问题