Languages
[Edit]
EN

Java convert string date time to epoch timestamp

3 points
Created by:
Root-ssh
115700

Quick solution:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class EpochToDateTimeExample {

    public static void main(String[] args) {

        String dateText = "2021-05-13 11:59:00.000";

        ZonedDateTime zonedDateTime = LocalDateTime.parse(
                dateText,
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
        ).atZone(ZoneId.of("UTC"));

        long epochMilli = zonedDateTime.toInstant().toEpochMilli();
        
        System.out.println(epochMilli); // 1620907140000
    }
}

Epoch to date time util

Based on above example we can build simple util:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class EpochToDateTimeUtil {

    public static long getEpochFromDate(String dateText) {
        ZonedDateTime zonedDateTime = LocalDateTime.parse(
                dateText,
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
        ).atZone(ZoneId.of("UTC"));

        return zonedDateTime.toInstant().toEpochMilli();
    }

    public static void main(String[] args) {
        System.out.println(
                getEpochFromDate("2021-05-13 00:00:00.000")); // 1620864000000

        System.out.println(
                getEpochFromDate("2021-05-13 11:59:00.000")); // 1620907140000
    }
}

Examples of different ZoneId

ZoneId.of("UTC")          // UTC (UTC+00:00)
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.

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join