1

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"
2
  • 2
    Please for your sanity use java.time, the modern Java date and time API, for your date and time work. SimpleDateFormat and Date have severe design problems and are long outdated. I recommend you don’t touch them. See the good answer by Arvind Kumar Avinash. Commented Jan 19, 2024 at 20:25
  • I cannot reproduce. From println(dateToMilliseconds(pdt)) I get 1705518869819 and no exception. The output is not correct, though. The correct millisecond value for your string pdt is 1 705 522 469 819. Commented Jan 19, 2024 at 20:32

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.*

1 Comment

Thank you for wanting to contribute. The SimpleDateFormat class is a notorious troublemaker of a class and best completely forgotten. In my most honest opinion helping users with how to use it is doing them an ill favour.
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.