Convert Date String into Epoch in Java [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-05 11:06:05

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.

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();
}

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();
Davy Jones

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!