How to parse dates in multiple formats using SimpleDateFormat

前端 未结 12 1664
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 08:41

I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.

here are the for

12条回答
  •  不要未来只要你来
    2020-11-22 09:18

    I'm solved this problem more simple way using regex

    fun parseTime(time: String?): Long {
        val longRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}.\\d{3}[Z]\$"
        val shortRegex = "\\d{4}+-\\d{2}+-\\d{2}+\\w\\d{2}:\\d{2}:\\d{2}Z\$"
    
        val longDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssXXX")
        val shortDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
    
        return when {
            Pattern.matches(longRegex, time) -> longDateFormat.parse(time).time
            Pattern.matches(shortRegex, time) -> shortDateFormat.parse(time).time
            else -> throw InvalidParamsException(INVALID_TIME_MESSAGE, null)
        }
    }
    

提交回复
热议问题