error: incompatible types: Object cannot be converted to LocalDate

1.1k views Asked by At

In my JSON response I receive the date as a timestamp value, e.g. below:

"dt":1620345600

I am trying to convert this into a LocalDate using the ThreeTen BP library. I have tried to apply a TypeConverter as follows

@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()
    }
}

Now I may be wrong i'm assuming the 'Object' in question is the SimpleDateFormat string. However I cant seem to find a way to plug the JSON response Int into the LocalDate DateTimeFormatter as that requires a String to be passed in. Any help appreciated

2

There are 2 answers

1
Maxim Tulupov On BEST ANSWER

When you use fun() = kompiler tries to guess return type. In your case try block returns Date, catch block returns String, common parent for these types - Object. You must explicitly set return type. Try this one and keep an eye on date format. It is incorrect in your code.

@TypeConverter
    fun timestampToDateTime(dt : Int?): LocalDate? {
        if (dt == null) {
            return null
        }
        return try {
            val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm")
            val netDate = Date(dt * 1000L)
            val sdf2 = sdf.format(netDate)
            LocalDate.parse(sdf2, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
        } catch (e : Exception) {
            //TODO handle exception
            null
        }
    }
4
anatoli On

DateTimeFormatter.ISO_LOCAL_DATE_TIME expect a following date format yyyy-MM-dd'T'hh:mm:ss

you can change first Formatter to

val sdf = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss")

and use DateTimeFormatter.ISO_LOCAL_DATE_TIME

UPDATE

whole solution:

try {
    val sdf = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss")
    val netDate = Date(dt * 1000L)
    val sdf2 = sdf.format(netDate)

    LocalDate localDate = LocalDate.parse(sdf2, DateTimeFormatter.ISO_LOCAL_DATE_TIME)

    Log.d("TAG", "date " + localDate.toString());
} catch (e : Exception) {
    e.printStackTrace()
}