【问题标题】:Why do I get a ParseException in this date? Android kotlin为什么我在这个日期收到 ParseException?安卓科特林
【发布时间】:2021-07-10 20:26:01
【问题描述】:

所以我正在创建一个函数来根据我设置的时间格式查看日期格式是否有效。函数如下所示:

    private fun isDateInvalid(time: String, timeFormat: String): Boolean {
    return try {
        val dateFormat = SimpleDateFormat(timeFormat, Locale.getDefault())
        dateFormat.isLenient = false
        dateFormat.parse(time)
        false
    } catch (e: ParseException){
        Log.d("Tag",e.toString())
        true
    }
}

所以在这个函数中,我将time 的参数传递为"07:45",将timeFormat 传递为HH:MM。我做错了什么?

【问题讨论】:

  • MM 代表月份,mm 代表分钟。
  • 另外,isLenient() 只是一个get 方法。您应该使用 setLenient()lenient 作为属性。

标签: android android-studio kotlin error-handling


【解决方案1】:

您的timeFormat 中有错误。 MM 代表“月”,mm 代表“分钟”。另外,考虑将isLenient 更改为setLenient()

这是我测试过的一个小程序:

import java.util.Locale
import java.text.SimpleDateFormat
import java.text.ParseException

fun isDateInvalid(time: String, timeFormat: String): Boolean {
    return try {
        val dateFormat = SimpleDateFormat(timeFormat, Locale.getDefault())
        dateFormat.setLenient(false)
        dateFormat.parse(time)
        false
    }
    catch (e: ParseException) {
        true
    }
}

fun main() 
{
    println("Date format is ${!isDateInvalid("07:45", "HH:mm")}")
    println("Date format is ${!isDateInvalid("07-45", "HH:mm")}")
}

输出:

Date format is true
Date format is false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多