如何将字符串Date转换为long millseconds

Daw*_*asi 79 java android epoch date-conversion milliseconds

我在字符串中有一个日期,类似于"2012年12月12日".如何将其转换为毫秒(长)?

Jon*_*Lin 136

使用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();
}
Run Code Online (Sandbox Code Playgroud)


Ram*_*ran 15

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


Ave*_*oes 9

看一下SimpleDateFormat可以解析a String并返回a Date和class getTime方法的Date类.


Ole*_*.V. 8

现在是时候有人为这个问题提供了现代答案.在2012年问到这个问题的时候,那些回答的答案也是很好的答案.为什么2016年发布的答案也使用了当时漫长的过时课程SimpleDateFormat,Date对我来说有点神秘.java.time,现代Java日期和时间API也称为JSR-310,使用起来非常好.您可以通过ThreeTenABP在Android上使用它,请参阅此问题:如何在Android项目中使用ThreeTenABP.

对于大多数用途,我建议使用自UTC时间开始的纪元以来的毫秒数.要获得这些:

    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);
Run Code Online (Sandbox Code Playgroud)

这打印:

1355270400000
Run Code Online (Sandbox Code Playgroud)

如果您需要在某个特定时区的某天开始时间,请指定该时区而不是UTC,例如:

            .atStartOfDay(ZoneId.of("Asia/Karachi"))
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,结果略有不同:

1355252400000
Run Code Online (Sandbox Code Playgroud)

还有一点需要注意,请记住为您提供一个区域设置DateTimeFormatter.我把12月份当作英语,还有其他语言,那个月被称为相同,所以请自己选择合适的语言环境.如果您没有提供语言环境,格式化程序将使用JVM的语言环境设置(在许多情况下可能有效),然后在具有不同语言环境设置的设备上运行应用程序时出现意外故障.


Dmi*_*sov 7