1

I am trying to set up a piece of code that willonly return true with legal dates. So with mask "MM/dd/yy" 02/02/62 would be legal but 66/66/66 would not.(However in that last case the date is being translated as Mon Aug 05 00:00:00 EST 71.

Here is the code:

fun legalDoB(): Boolean {
    val dobString = dobTextId.text.toString()
    val df = SimpleDateFormat("MM/dd/yy")
    try {
        val date:Date = df.parse(dobString)
        Log.d(DEBUG,"Legal Date $date")
        return true
    } catch (e: ParseException){
        Log.d(DEBUG,"NOT Legal Date")
        return false
    }
    return false
Tony Sherman
  • 285
  • 1
  • 6
  • 18

1 Answers1

1

This answer comes from jAnA on the SO question: ( Java: Check the date format of current string is according to required format or not )

that is to use: .setLenient(false).

In Kotlin that means my original code should be:

fun legalDoB(): Boolean {
    val dobString = dobTextId.text.toString()
    val df = SimpleDateFormat("MM/dd/yy")
    df.isLenient = false
    try {
        val date:Date = df.parse(dobString)
        Log.d(DEBUG,"Legal Date $date")
        return true
    } catch (e: ParseException){
        Log.d(DEBUG,"NOT Legal Date")
        return false
    }
    return false
}
Tony Sherman
  • 285
  • 1
  • 6
  • 18