如何将日期转换为毫秒

开始:

我要转换String myDate = "2014/10/29 18:10:45"long ms (i.e. currentinmlilies)我在Google上寻找它,但我只能找到如何将ms转换date

注意:为了清楚起见,我想从日期中以1970/1/1格式获取ms。

路易吉·门多萨(Luiggi Mendoza):

您没有Date,您拥有String日期表示形式。您应该将转换StringDate,然后获取毫秒。要将a转换String为a Date,反之亦然,请使用SimpleDateFormatclass。

这是您想要/需要做的事的一个例子(假设这里不涉及时区):

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章