我要转换String myDate = "2014/10/29 18:10:45"
成long ms (i.e. currentinmlilies)
?我在Google上寻找它,但是我只能找到如何将ms转换为date。
注意:为了清楚起见,我想从1970/1/1格式的日期中获取ms。
您没有Date
,您拥有String
日期的表示形式。您应该将转换String
为Date
,然后获取毫秒。要将a转换String
为a Date
,反之亦然,请使用SimpleDateFormat
class。
这是您想要/需要做的事的一个例子(假设这里不涉及时区):
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之间的毫秒数。
使用自Java 8以来可用的新的日期/时间API:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句