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
You're probably looking for
ofInstant
:Also, instead of working with
Int
, you should probably work withLong
.