user804979 user804979 - 6 months ago 15
Java Question

Convert a date format in epoch

I have a string with a date format such as

Jun 13 2003 23:11:52.454 UTC


containing millisec... which I want to convert in epoch.
Is there an utility in Java I can use to do this conversion?

Answer

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

public static void main(String[] args) throws Exception
{
    String str = "Jun 13 2003 23:11:52.454 UTC";
    SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
    Date date = df.parse(str);
    long epoch = date.getTime();
    System.out.println(epoch); // 1055545912454
}

Date.getTime() returns the epoch time in milliseconds.

Comments