如何在Android中检查日期是否有效?

huangapple go评论63阅读模式
英文:

How can I check if a date is valid in Android?

问题

我已经有一个用来验证日期的函数。问题是,我没有验证2月30日这样的情况。我想也许在Android上有一种更简单的本地方法来进行这种验证。你能帮我吗?

我的当前验证函数是:

fun isDateOfBirthValid(date: String): Boolean {
    if (date.length != 10) {
        return false
    }

    val day = date.substring(0, 2).toIntOrNull()
    val month = date.substring(3, 5).toIntOrNull()
    val year = date.substring(6, 10).toIntOrNull()

    if (day == null || month == null || year == null) {
        return false
    }

    if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900) {
        return false
    }

    val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
    if (LocalDate.parse(date, formatter) > LocalDate.now()) {
        return false
    }

    return true
}
英文:

I already have a function to validate my date. The problem is that I don't have the verification for February 30, for example. I think that maybe there's an easier native way to do this validation on Android. Can you help me?

My current validating function is:

fun isDateOfBirthValid(date: String): Boolean {
    if (date.length != 10) {
        return false
    }

    val day = date.substring(0, 2).toIntOrNull()
    val month = date.substring(3, 5).toIntOrNull()
    val year = date.substring(6, 10).toIntOrNull()

    if (day == null || month == null || year == null) {
        return false
    }

    if (day &lt; 1 || day &gt; 31 || month &lt; 1 || month &gt; 12 || year &lt; 1900) {
        return false
    }

    val formatter = DateTimeFormatter.ofPattern(&quot;dd-MM-yyyy&quot;)
    if (LocalDate.parse(date, formatter) &gt; LocalDate.now()) {
        return false
    }

    return true
}

答案1

得分: 2

只尝试解析日期就足够了。如果抛出异常,你就知道它是不正确的。或者当解析后的日期与输入不匹配时。就像这样,例如

fun isDateOfBirthValid(date: String): Boolean {
    try {
        val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
        val localDate = LocalDate.parse(date, formatter)
        if (!formatter.format(localDate).equals(date) || localDate > LocalDate.now()) {
            return false
        }
        return true
    } catch (e: Exception) {
        return false
    }
}
英文:

Just trying to parse the date is enough. If it throws an exception you know it is incorrect. Or when the parsed date doesn't match the input. So like this for example

fun isDateOfBirthValid(date: String): Boolean {
    try {
        val formatter = DateTimeFormatter.ofPattern(&quot;dd-MM-yyyy&quot;)
        val localDate = LocalDate.parse(date, formatter)
        if (!formatter.format(localDate).equals(date) || localDate &gt; LocalDate.now()) {
            return false
        }
        return true
    } catch (e: Exception) {
        return false
    }
}

答案2

得分: 0

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

object DateValidator {

    fun isDateValid(dateStr: String): Boolean {
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        sdf.isLenient = false // This ensures strict date validation

        return try {
            val date = sdf.parse(dateStr)
            // If the parsing succeeds, the date is valid
            true
        } catch (e: ParseException) {
            // If an exception is caught, the date is not valid
            false
        }
    }
}

使用方法:

val inputDate = "2023-07-31"
val isValidDate = DateValidator.isDateValid(inputDate)

希望这有所帮助。

英文:
import java.text.SimpleDateFormat
import java.util.*

object DateValidator {

    fun isDateValid(dateStr: String): Boolean {
        val sdf = SimpleDateFormat(&quot;yyyy-MM-dd&quot;, Locale.getDefault())
        sdf.isLenient = false // This ensures strict date validation

        return try {
            val date = sdf.parse(dateStr)
            // If the parsing succeeds, the date is valid
            true
        } catch (e: ParseException) {
            // If an exception is caught, the date is not valid
            false
        }
    }
}

usage

val inputDate = &quot;2023-07-31&quot;
val isValidDate = DateValidator.isDateValid(inputDate)

hope this helps

huangapple
  • 本文由 发表于 2023年7月31日 19:42:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定