Parse string date to millis in kotlin

141 Views Asked by At

I am using SDF to parse a string date to millis with below code

private fun dateToMilliseconds(dateValue: String): Long? {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
val date: Date
try {
    date = sdf.parse(dateValue)!!
    return date.time
} catch (e: Exception) {
    e.printStackTrace()
}
return null
}

And the date is val pdt = "2024-01-17T20:14:29.819Z"

On running it in android I get the exception for unparseable date

java.text.ParseException: Unparseable date: "2024-01-17T20"
3

There are 3 best solutions below

1
Hossein Shahmohammadi On BEST ANSWER

I used your code in IntellijIdea and Android Studio and it works properly. Make sure you imported below classes and not using other same name classes:

import java.text.SimpleDateFormat
import java.util.*
0
Hoàng Vũ Anh On

You can try this:

fun parseStringDateToMillis(dateString: String, pattern: String): Long {
    val dateFormat = SimpleDateFormat(pattern)
    val date = dateFormat.parse(dateString)
    return date?.time ?: 0L
}

use this function in an activity or fragment:

   val dateString = "2022-01-15T12:30:45"
   val pattern = "yyyy-MM-dd'T'HH:mm:ss"
   val millis = parseStringDateToMillis(dateString, pattern)

   println("Milliseconds: $millis")
0
Arvind Kumar Avinash On

java.time

The java.util date-time API and their corresponding parsing/formatting type, SimpleDateFormat are outdated and error-prone. In March 2014, the modern Date-Time API supplanted the legacy date-time API. Since then, it has been strongly recommended to switch to java.time, the modern date-time API.

You can declare an optional pattern inside a [] with a DateTimeFormatter. In the following demo, you can see that a single DateTimeFormatter can parse all four strings.

After parsing the date-time string, you can convert the resulting LocalDateTime into a ZonedDateTime in the system's timezone. In the final step, you convert the ZonedDateTime into an Instant and get from it the milliseconds since the epoch.

Demo:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        var dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH[:mm[:ss[.SSS]]]", Locale.ENGLISH);
        Stream.of(
                "2024-01-17T20",
                "2024-01-17T20:10",
                "2024-01-17T20:10:05",
                "2024-01-17T20:10:05.123"
        ).forEach(s -> {
            var ldt = LocalDateTime.parse(s, dtf);
            var millis = ldt.atZone(ZoneId.systemDefault())
                            .toInstant()
                            .toEpochMilli();
            System.out.println(ldt + " -> " + millis);
        });
    }
}

Output:

2024-01-17T20:00 -> 1705521600000
2024-01-17T20:10 -> 1705522200000
2024-01-17T20:10:05 -> 1705522205000
2024-01-17T20:10:05.123 -> 1705522205123

ONLINE DEMO

Learn about the modern date-time API from Trail: Date Time