Home > Net >  Kotlin extract time form the date
Kotlin extract time form the date

Time:05-17

I have a date with that format: 2027-02-14T14:20:00.000

I would like to take hours and minutes from it like in that case: 14:20

I was trying to do something like this:

val firstDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse("2027-02-14T14:20:00.000")
val firstTime = SimpleDateFormat("H:mm").format(firstDate)

but I got crash java.text.ParseException: Unparseable date

How to take hours and minutes from that string ?

CodePudding user response:

One of the RECOMMENDED WAYs

In case you can use java.time, here's a commented example:

import java.time.LocalDateTime
import java.time.LocalDate
import java.time.format.DateTimeFormatter

fun main() {
    // example String
    val input = "2027-02-14T14:20:00.000"
    // directly parse it to a LocalDateTime
    val localDateTime = LocalDateTime.parse(input)
    // print the (intermediate!) result
    println(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
    // then extract the date part
    val localDate = localDateTime.toLocalDate()
    // print that
    println(localDate)
}

This outputs 2 values, the intermediate LocalDateTime parsed and the extracted LocalDate (the latter simply invoking its toString() method implicitly):

2027-02-14T14:20:00
2027-02-14

NOT RECOMMENDED but still possible:

Still use the outdated API (might be necessary when it comes to large amounts of legacy code, which I doubt you will find written in Kotlin):

import java.text.SimpleDateFormat

fun main() {
    val firstDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
                            .parse("2027-02-14T14:20:00.000")
    val firstTime = SimpleDateFormat("yyyy-MM-dd").format(firstDate)
    println(firstTime)
}

Output:

2027-02-14
  • Related