Search code examples
spring-bootdatekotlininitializationunix-timestamp

How to check Date instance init success or not in Kotlin?


I am coding a function to check if an Integer x is UNIX timestamp format or not. Current I'm think the solution is check if the program can initialize an Date instance from x or not. But I can't found how to check it in Kotlin. Please help me with it.

Note: The enviroment I use:

  • SpringBoot 2.5
  • Kotlin 1.3.5

Udate 1: I came up with a way using try catch but I guess my approach to the "UNIX timestamp" problem is wrong. Seem like with every Integer a new Date can be created in below code.

val x: Long = 123456;
try {
    val a = Date(x)
} catch (e : Exception) {
    throw DataInvalidException("x must be UNIX timestamp")
}

Solution

  • A Unix timestamp is just the number of seconds since 1970-01-01 00:00:00Z. So any number is a valid Unix timestamp (including 123456, which if I've calculated correctly is just 1970-01-02 10:17:36Z).

    If you want to put any restrictions on the range of dates and/or times that you will accept, then that can of course be done; but you'd have to understand that you'd be ruling out genuine timestamps.