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
SimpleDateFormatandDatehave severe design problems and are long outdated. I recommend you don’t touch them. See the good answer by Arvind Kumar Avinash.println(dateToMilliseconds(pdt))I get1705518869819and no exception. The output is not correct, though. The correct millisecond value for your stringpdtis 1 705 522 469 819.