This question already has an answer here:
-
Convert a date format in epoch
5 answers
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).
Date.getTime()
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();
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();
}