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

I have a date inside a string, something like "12-December-2012". How can I convert this into milliseconds (long)?

This question is related to java android epoch milliseconds date-conversion

The answer is


  • First convert string to java.util.Date using date formatter
  • Use getTime() to obtain count of millisecs from date

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.


Easiest way is used the Date Using Date() and getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

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


Take a look to SimpleDateFormat class that can parse a String and return a Date and the getTime method of Date class.


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

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();

you can use the simpleDateFormat to parse the string date.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to epoch

How to extract epoch from LocalDate and LocalDateTime? converting epoch time with milliseconds to datetime PostgreSQL: how to convert from Unix epoch to date? How to convert a string Date to long millseconds How do I get the unix timestamp in C as an int? Convert python datetime to epoch with strftime How do I get epoch time in C#? Android Get Current timestamp? How can I convert a datetime object to milliseconds since epoch (unix time) in Python? Convert a date format in epoch

Examples related to milliseconds

Timestamp with a millisecond precision: How to save them in MySQL How to get milliseconds from LocalDateTime in Java 8 Converting milliseconds to minutes and seconds with Javascript How to convert time milliseconds to hours, min, sec format in JavaScript? Getting date format m-d-Y H:i:s.u from milliseconds Get DateTime.Now with milliseconds precision How to convert milliseconds to seconds with precision How to convert a string Date to long millseconds How can I get the count of milliseconds since midnight for the current? milliseconds to days

Examples related to date-conversion

Converting unix time into date-time via excel Conversion failed when converting date and/or time from character string in SQL SERVER 2008 Go / golang time.Now().UnixNano() convert to milliseconds? sql server Get the FULL month name from a date How to convert a string Date to long millseconds Date and time conversion to some other Timezone in java How to get the integer value of day of week Convert one date format into another in PHP