How to convert a string Date to long millseconds How to convert a string Date to long millseconds java java

How to convert a string Date to long millseconds


Using SimpleDateFormat

String string_date = "12-December-2012";SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");try {    Date d = f.parse(string_date);    long milliseconds = d.getTime();} catch (ParseException e) {    e.printStackTrace();}


SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");Date date = (Date)formatter.parse("12-December-2012");long mills = date.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.