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

前端 未结 13 1395
耶瑟儿~
耶瑟儿~ 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 08:06

    Since Z and XXX are different, I've implemented the following workaround:

    // This is a workaround from Z to XXX timezone format
    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") {
    
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
            StringBuffer rfcFormat = super.format(date, toAppendTo, pos);
            return rfcFormat.insert(rfcFormat.length() - 2, ":");
        }
    
        @Override
        public Date parse(String text, ParsePosition pos) {
            if (text.length() > 3) {
                text = text.substring(0, text.length() - 3) + text.substring(text.length() - 2);
            }
            return super.parse(text, pos);
        }
    }
    

提交回复
热议问题