Creating typeconvertor to convert Int timestamp to LocalDate

432 views Asked by At

What would be the best way to go about this. I am using 2 different APIs and one returns a date as a String and the other returns date as an Int timestamp in the format of e.g. 162000360

I was using the ThreeTen backport for Date/Time classes. I have successfully created a type convertor for the date I get back as a String - provided below

@TypeConverter
@JvmStatic
fun stringToDate(str: String?) = str?.let {
    LocalDate.parse(it, DateTimeFormatter.ISO_LOCAL_DATE)
}

@TypeConverter
@JvmStatic
fun dateToString(dateTime: LocalDate?) = dateTime?.format(DateTimeFormatter.ISO_LOCAL_DATE)

I'm struggling to replicate the same for the Int timestamp as the DateTimeFormatter requires a String passed into it and won't allow an Int. Any help is much appreciated

Edit: Have tried the following implementation

@TypeConverter
@JvmStatic
fun timestampToDateTime(dt : Int?) = dt?.let {
    try {
        val sdf = SimpleDateFormat("yyyy-MMM-dd HH:mm")
        val netDate = Date(dt * 1000L)
        val sdf2 = sdf.format(netDate)

        LocalDate.parse(sdf2, DateTimeFormatter.ISO_LOCAL_DATE_TIME)

    } catch (e : Exception) {
        e.toString()
    }
}

Probably a bit aroundabout but hopefully it works ok

1

There are 1 answers

0
Alexey Soshin On

You're probably looking for ofInstant:

fun intToDate(int: Int?) = int?.let {
    LocalDate.ofInstant(Instant.ofEpochMilli(it.toLong()), ZoneId.systemDefault())
}

println(intToDate(162000360)) // 1970-01-02

Also, instead of working with Int, you should probably work with Long.