Home > OS >  How I can validate a timestamp of a specific format?
How I can validate a timestamp of a specific format?

Time:06-08

I'm getting values like the next from an API "2022-01-01T00:00:00.000 02:00" and I want to do a validator for dates, to check if the timestamp received is valid or not in the future.

I'm reading about SimpleDateFormat, but I don't know if this is the best way to do that in kotlin.

In java I would do like this:

public static boolean isValidDate(String inDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:ms");
        dateFormat.setLenient(false);
        try {
            dateFormat.parse(inDate.trim());
        } catch (ParseException pe) {
            return false;
        }
        return true;
    }

Thank you

CodePudding user response:

If you are trying to validate the value in string you could use the similar logic as follows:

 private val pattern: Pattern? = null
private var matcher: Matcher? = null

private val DATE_PATTERN =
    "(0?[1-9]|1[012]) [/.-] (0?[1-9]|[12][0-9]|3[01]) [/.-] ((19|20)\\d\\d)"


/**
 * Validate date format with regular expression
 * @param date date address for validation
 * @return true valid date format, false invalid date format
 */
fun validate(date: String?): Boolean {
    matcher = pattern.matcher(date)
    return if (matcher.matches()) {
        matcher.reset()
        if (matcher.find()) {
            val day: String = matcher.group(1)
            val month: String = matcher.group(2)
            val year: Int = matcher.group(3).toInt()
            if (day == "31" &&
                (month == "4" || month == "6" || month == "9" || month == "11" || month == "04" || month == "06" || month == "09")
            ) {
                false // only 1,3,5,7,8,10,12 has 31 days
            } else if (month == "2" || month == "02") {
                //leap year
                if (year % 4 == 0) {
                    !(day == "30" || day == "31")
                } else {
                    !(day == "29" || day == "30" || day == "31")
                }
            } else {
                true
            }
        } else {
            false
        }
    } else {
        false
    }
}

Ref: Date Validation in Android Or If you are trying to validate after parsing the string you could ref this blog post

Note: These examples are in Java, but the logic could be easily converted to Kotlin.

Hope this helps!

  • Related