Search code examples
androidandroid-studiokotlinthreetenbp

error: incompatible types: Object cannot be converted to LocalDate


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


Solution

  • 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
            }
        }