9

Is there a way to convert a given Date String into Milliseconds (Epoch Long format) in java? Example : I want to convert

public static final String date = "04/28/2016"; 

into milliseconds (epoch).

Ashley
  • 441
  • 2
  • 8
  • 27

4 Answers4

15

The getTime() method of the Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Paul Ostrowski
  • 1,968
  • 16
  • 21
  • I'm getting `Cannot make a static reference to the non-static method getTime() from the type Date`, so I had to use `new Date().getTime()` instead. – CyberMew Jan 04 '19 at 14:41
8

You can simply parse it to java.util.Date using java.text.SimpleDateFormat and call it's getTime() function. It will return the number of milliseconds since Jan 01 1970.

public static final String strDate = "04/28/2016";
try {
    Long millis = new SimpleDateFormat("MM/dd/yyyy").parse(strDate).getTime();
} catch (ParseException e) {
    e.printStackTrace();
}
aichy
  • 81
  • 2
  • 6
  • does parse work on date object? – AJC Jul 12 '17 at 21:44
  • `Date d = SimpleDateFormat(String pattern).parse(String strDate);` It parses a string (formatted date) by a pattern specified and returns a `java.util.Date` object. – aichy Jul 18 '17 at 06:34
  • [Specified in Java8SE Doc](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html#parse-java.lang.String-java.text.ParsePosition-) – aichy Jul 19 '17 at 14:48
  • Right. That was my understanding too. But the snippet in the answer confused me as there were no mention that date was a String – AJC Jul 19 '17 at 16:10
  • Yes. Sorry about that. I have edited the answer and renamed the variable to make it more clear. – aichy Jul 20 '17 at 06:29
1

You can create a Calendar object and then set it's date to the date you want and then call its getTimeInMillis() method.

Calendar c = new Calendar.getInstance();
c.set(2016, 3, 28);
c.getTimeInMillis();

If you want to convert the String directly into the date you can try this:

String date = "4/28/2016";
String[] dateSplit = date.split("/");
c.set(Integer.valueOf(dateSplit[2]), Integer.valueOf(dateSplit[0]) - 1, Integer.valueOf(dateSplit[1]));
c.getTimeInMillis();
Albert
  • 337
  • 1
  • 10
0

You will need to use Calendar instance for getting millisecond from epoch

try {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    java.util.Date d = sdf.parse("04/28/2016");
    /*
     * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
     */
    System.out.println(d.getTime());
    //OR
    Calendar cal = Calendar.getInstance();
    cal.set(2016, 3, 28);
    //the current time as UTC milliseconds from the epoch.
    System.out.println(cal.getTimeInMillis());
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
Davy Jones
  • 111
  • 1
  • 2