How to format in Kotlin date in string or timestamp to my preferred format?

beginner992 picture beginner992 · Aug 7, 2019 · Viewed 18.3k times · Source

I'm getting date data from weather API in two versions. The first one is just string like this: 2019-08-07 09:00:00 and like this: 1565209665. How change it to the just name of the day or day and month? For example: Monday, August.

I tried something like this in few configurations but it works only in full version. If I cat something then it throws an error:

    var date = list.get(position).dt_txt
    val formatter = DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter()
    formatter.parse(date)

Answer

Ben Shmuel picture Ben Shmuel · Aug 8, 2019

First API format:

val firstApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val date = LocalDate.parse("2019-08-07 09:00:00" , firstApiFormat)

Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August

Second API format:

val secondApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val timestamp = 1565209665.toLong() // timestamp in Long


val timestampAsDateString = java.time.format.DateTimeFormatter.ISO_INSTANT
            .format(java.time.Instant.ofEpochSecond(timestamp))

Log.d("parseTesting", timestampAsDateString) // prints 2019-08-07T20:27:45Z


val date = LocalDate.parse(timestampAsDateString, secondApiFormat)

Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August