androidkotlindatedatetimesimpledateformat

Kotlin extract time form the date


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 ?


Solution

  • A RECOMMENDED WAY

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

    import java.time.LocalDateTime
    import java.time.LocalTime
    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 time part
        val localTime = localDateTime.toLocalTime()
        // print that keeping the full format
        println(localTime.format(DateTimeFormatter.ISO_LOCAL_TIME))
    }
    

    This outputs 2 values, the intermediate LocalDateTime parsed and the extracted LocalTime:

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

    NOT RECOMMENDED while 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("HH:mm:ss").format(firstDate)
        println(firstTime)
    }
    

    Output:

    14:20:00