如何将日期转换为毫秒 [英] How to convert a date to milliseconds
问题描述
我想将 String myDate =2014/10/29 18:10:45
转换为
long ms(即currentinmlilies)
?我在Google上查找,但我只能找到如何将 ms 转换为 date 。
I want to convert String myDate = "2014/10/29 18:10:45"
to
long ms (i.e. currentinmlilies)
? I look for it on Google, but I can only find how to convert ms to date.
注意:为了说清楚,我想从1970/1/1格式的日期获得ms。
Note: To make it clear, I want to get the ms from the date in 1970/1/1 format.
推荐答案
你没有日期
,你有字符串
表示日期。您应该将 String
转换为 Date
,然后获取毫秒数。要将字符串
转换为日期
,反之亦然,您应该使用 SimpleDateFormat
class。
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
以下是您想要/需要做的示例(假设此处不涉及时区):
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
但是,要小心,因为在Java中,获得的毫秒数是所需时期与1970-01之间的毫秒数-01 00:00:00。
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
使用自Java 8以来可用的新日期/时间API:
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
这篇关于如何将日期转换为毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!