0

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

Víctor Martín
  • 3,352
  • 7
  • 48
  • 94
  • This is best solution you will try once -https://github.com/Kotlin/kotlinx-datetime – Sandesh Khutal Jun 06 '22 at 15:21
  • 2
    Nothing wrong with doing the exact same thing in Kotlin! – Egor Jun 06 '22 at 15:30
  • I think you don't need to validate the value came from API. just try to parse that and use it. if parse failed then handle this state. meanwhile, standard APIs usually send time values in timestamp format. – Pejman Azad Jun 06 '22 at 16:51
  • Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. – Ole V.V. Jun 06 '22 at 17:17
  • `OffsetDateTime.parse("2022-01-01T00:00:00.000+02:00").isAfter(OffsetDateTime.now())` will yield `true` if the timestamp is in the future. And will throw `DateTimeParseException` if the format or the date is invalid, so surround with `try`-`catch`. – Ole V.V. Jun 06 '22 at 17:19

1 Answers1

1

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!

rahu1613
  • 111
  • 9