我在字符串中有一个日期,类似于“2012年12月12日”。 如何将其转换为毫秒(长)?
答案 0 :(得分:131)
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();
}
答案 1 :(得分:15)
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();
答案 2 :(得分:9)
查看可以解析SimpleDateFormat
的{{1}}类并返回String
和Date
类getTime
方法。
答案 3 :(得分:7)
答案 4 :(得分:7)
现在是时候有人为这个问题提供现代答案了。在2012年问到这个问题的时候,那些回答的答案也是很好的答案。为什么2016年发布的答案也使用当时已过时的课程SimpleDateFormat
和Date
对我来说有点神秘。 java.time
,现代Java日期和时间API,也称为JSR-310,使用起来非常好。您可以通过ThreeTenABP在Android上使用它,请参阅this question: How to use ThreeTenABP in Android Project。
对于大多数用途,我建议使用自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);
打印:
1355270400000
如果您需要某个特定时区的某天开始时间,请指定该时区而不是UTC,例如:
.atStartOfDay(ZoneId.of("Asia/Karachi"))
正如预期的那样,结果略有不同:
1355252400000
需要注意的另一点是,请记住为DateTimeFormatter
提供区域设置。我把12月份当作英语,还有其他语言,那个月被称为相同,所以请自己选择合适的语言环境。如果您没有提供语言环境,格式化程序将使用JVM的语言环境设置,这可能在许多情况下有效,然后当您在具有不同语言环境设置的设备上运行应用程序时,有一天意外失败。
答案 5 :(得分:3)
您可以使用simpleDateFormat来解析字符串日期。
答案 6 :(得分:0)
使用simpledateformat可以轻松实现它。
1)首先使用simpledateformatter将字符串转换为java.Date。
2)使用getTime方法从日期获得毫秒数
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();
}
}
更多示例点击here
答案 7 :(得分:-1)
最简单的方法是使用Date Using Date()和getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
答案 8 :(得分:-1)
尝试以下代码
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();