How to convert a string Date to long millseconds

前端 未结 9 2103
你的背包
你的背包 2020-11-29 07:40

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

相关标签:
9条回答
  • 2020-11-29 08:38

    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

    0 讨论(0)
  • 2020-11-29 08:38

    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();
    
    0 讨论(0)
  • 2020-11-29 08:40

    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.

    0 讨论(0)
提交回复
热议问题