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

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

    The following class can be used to convert the string to date when pattern doesn't aware of it.

        import java.text.SimpleDateFormat;
        import java.util.Arrays;
        import java.util.Date;
        import java.util.List;
    
    /**
     * StringToDateFormater is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for
     * formatting (date → text), parsing (text → date), and normalization.
     * 
     * This class is mainly used for convert the date from string. It should be used only when date pattern doesn't aware of
     * it. 
     *
     */
    public class StringToDateFormater extends SimpleDateFormat {
    
        private static final List DATE_SUPPORTED_FORMAT_LIST = Arrays.asList("yyyyMMddHHmmss", "yyyyMMddHHmm",
                "yyyyMMddHHmm", "yyyyMMddHH", "yyyyMMdd", "yyyyMMddHHmmssSS");
    
        /**
         * 
         */
        private static final long serialVersionUID = -1732857502488169225L;
    
        /**
         * @param pattern
         */
        public StringToDateFormater() {
        }
    
        @Override
        public Date parse(String source) {
            Date date = null;
    
            SimpleDateFormat dateFormat = null;
            for (String format : DATE_SUPPORTED_FORMAT_LIST) {
                dateFormat = new SimpleDateFormat(format);
                try {
                    return dateFormat.parse(source);
                } catch (Exception exception) {
    
                }
    
            }
    
            return date;
        }
    }
    

提交回复
热议问题