How to Convert Date String to Epoch Milliseconds in Java
How can we convert a String
representation of a date into long
milliseconds in Java?
Suppose we want to get the epoch milliseconds of the date below.
String dateStr = "2022/07/03 12:12:12";
1. Using Java 8’s LocalDateTime
We can parse the date string into a LocalDateTime
object using the DateTimeFormatter
, specifying the format of the date string.
Then, we can apply a time zone, or ZonedDateTime
, to the LocalDateTime
object to provide context into the exact moment the datetime occurred (e.g. 6PM can refer to different points in time depending on the time zone).
Next, we can convert the time a single moment in UTC by converting to an Instant
.
Finally, we can call toEpochMillis()
.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.parse(dateStr, dtf);
long millis = ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
toEpochMilli()
carries nanosecond-precision timestamps, so callingtoEpochMilli()
ignores the nanosecond, fractional portion.
2. Using SimpleDateFormat
With SimpleDateFormat
, we can simply pass our date format into the constructor and parse dateStr
to get a Date
object.
Calling getTime()
will return the milliseconds.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(dateStr);
long millis = date.getTime();
Keep in mind that
SimpleDateFormat
is not thread-safe.