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

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

    Android SimpleDateFormat is different from Java 7 SDK and does not support 'X' to parse ISO 8601. You can use the 'Z' or 'ZZZZZ' styles to format and programatically set the time zone to UTC. Here is a util class:

    public class DateUtil {
    
        public static final String iso8601DatePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
        public static final DateFormat iso8601DateFormat = new SimpleDateFormat(iso8601DatePattern);
        public static final TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    
        static {
            iso8601DateFormat.setTimeZone(utcTimeZone);
        }
    
        public static String formatAsIso8601(Date date) {
    
            return iso8601DateFormat.format(date);
        }
    }
    

提交回复
热议问题