I have a date inside a string, something like \"12-December-2012\". How can I convert this into milliseconds (long)?
using simpledateformat you can easily achieve it.
1) First convert string to java.Date using simpledateformatter.
2) Use getTime method to obtain count of millisecs from date
public class test {
public static void main(String[] args) {
String currentDate = "01-March-2016";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date parseDate = f.parse(currentDate);
long milliseconds = parseDate.getTime();
}
}
more Example click here
Try below code
SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
Date d = null;
try {
d = f.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
long timeInMillis = d.getTime();
It’s about time someone provides the modern answer to this question. In 2012 when the question was asked, the answers also posted back then were good answers. Why the answers posted in 2016 also use the then long outdated classes SimpleDateFormat
and Date
is a bit more of a mystery to me. java.time
, the modern Java date and time API also known as JSR-310, is so much nicer to work with. You can use it on Android through the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project.
For most purposes I recommend using the milliseconds since the epoch at the start of the day in UTC. To obtain these:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
String stringDate = "12-December-2012";
long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
System.out.println(millisecondsSinceEpoch);
This prints:
1355270400000
If you require the time at start of day in some specific time zone, specify that time zone instead of UTC, for example:
.atStartOfDay(ZoneId.of("Asia/Karachi"))
As expected this gives a slightly different result:
1355252400000
Another point to note, remember to supply a locale to your DateTimeFormatter
. I took December to be English, there are other languages where that month is called the same, so please choose the proper locale yourself. If you didn’t provide a locale, the formatter would use the JVM’s locale setting, which may work in many cases, and then unexpectedly fail one day when you run your app on a device with a different locale setting.