EN
Java convert string date time to epoch timestamp
3 points
Quick solution:
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.ZoneId;
3
import java.time.ZonedDateTime;
4
import java.time.format.DateTimeFormatter;
5
6
public class EpochToDateTimeExample {
7
8
public static void main(String[] args) {
9
10
String dateText = "2021-05-13 11:59:00.000";
11
12
ZonedDateTime zonedDateTime = LocalDateTime.parse(
13
dateText,
14
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
15
).atZone(ZoneId.of("UTC"));
16
17
long epochMilli = zonedDateTime.toInstant().toEpochMilli();
18
19
System.out.println(epochMilli); // 1620907140000
20
}
21
}
Based on above example we can build simple util:
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.ZoneId;
3
import java.time.ZonedDateTime;
4
import java.time.format.DateTimeFormatter;
5
6
public class EpochToDateTimeUtil {
7
8
public static long getEpochFromDate(String dateText) {
9
ZonedDateTime zonedDateTime = LocalDateTime.parse(
10
dateText,
11
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
12
).atZone(ZoneId.of("UTC"));
13
14
return zonedDateTime.toInstant().toEpochMilli();
15
}
16
17
public static void main(String[] args) {
18
System.out.println(
19
getEpochFromDate("2021-05-13 00:00:00.000")); // 1620864000000
20
21
System.out.println(
22
getEpochFromDate("2021-05-13 11:59:00.000")); // 1620907140000
23
}
24
}
xxxxxxxxxx
1
ZoneId.of("UTC") // UTC (UTC+00:00)
2
ZoneId.of("Europe/Paris") // Europe/Paris (UTC+02:00)
In java there is lack of an enum and we need to pass the String to the ZoneId.of("") method.