在 Kotlin Android 中解析日期的正确方法(最低 Android 版本 21)。我的解析不工作

Correct way to parse Date in Kotlin Android (Minimum Android Version 21). My parse is not working

我想以此格式解析此日期 2021-11-03T14:09:31.135Z (message.created_at)

我的代码是这样的:

val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS")
var convertedDate = Date()
try {
    convertedDate = dateFormat.parse(message.created_at)
} catch (e: ParseException) {
    e.printStackTrace()
}

解析失败

嗯,格式不完全是字符串的样子:

  • 日期和时间之间有一个 space 而不是 T 文字
  • 你最后没有偏移符号
  • 您正在使用 hh,这是 12 小时格式。请改用 HH

这种格式应该可以:

yyyy-MM-dd'T'HH:mm:ss.SSSX

但是,请注意 DateSimpleDateFormat 已过时并且 troublesome. Use java.time instead. If your Android API level appears to be too low, you could use ThreeTen Backport

试一试


fun main() {
    val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS")
    var convertedDate = Date()
    try {
        convertedDate = dateFormat.parse("2021-11-03T14:09:31.135Z")
        println(convertedDate)
    } catch (e: ParseException) {
        e.printStackTrace()
    }
}

不要使用 SimpleDateFormat 它很长 outdated and troublesome
使用DateTimeFormatter解析日期。

 fun parseDate() {
        var formatter: DateTimeFormatter? = null
        val date = "2021-11-03T14:09:31.135Z" // your date string
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX") // formatter
            val dateTime: ZonedDateTime = ZonedDateTime.parse(date, parser) // date object
            val formatter2: DateTimeFormatter =
                DateTimeFormatter.ofPattern("EEEE, MMM d : HH:mm") // if you want to convert it any other format
            Log.e("Date", "" + dateTime.format(formatter2))
        }
    }

输出: 11 月 3 日,星期三:14:09

要在 android 8 下面使用它,请使用 desugaring

如果你的最低 API 等级是 21,你可以使用 API Desugaring, find some nice explanations about it here

一旦启用 API 脱糖,您就可以直接将 ISO String 解析为 OffsetDateTime:

val convertedDate = OffsetDateTime.parse(message.created_at)

您刚刚在日期格式字符串中遗漏了“T”。使用此解决方案进行日期解析。

fun formatDate(inputDate: String) {
    var convertedDate = Date()
    val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ", Locale.getDefault())
    try {
        convertedDate = dateFormat.parse(inputDate)
        print("Parsed date $convertedDate")
    } catch (ignored: ParseException) {
    }

    //if you wish to change the parsed date into another formatted date
    val dfOutput = SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault())
    val str :String = dfOutput.format(convertedDate)
    print("Formatted date $str")
}

只需将您的“message.created_at”作为输入参数传递。有关更多日期时间格式,请查看 Android 开发者网站的官方文档。 SimpleDateFormat | Android Developers 您将在此处获得所有可能的日期格式。

干杯..!