如何使用LocalDateTime从Java 8中的String创建以毫秒为单位的长时间? [英] How to create a long time in Milliseconds from String in Java 8 with LocalDateTime?

查看:452
本文介绍了如何使用LocalDateTime从Java 8中的String创建以毫秒为单位的长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入日期,格式为yyyy-MM-dd_HH:mm:ss.SSS,并将其转换为long这样:

I have an input date in format yyyy-MM-dd_HH:mm:ss.SSS and convert it to long this way:

SimpleDateFormat simpleDateFormat = 
                   new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
try {
    Date date = simpleDateFormat.parse(lapTime);
    time = date.getTime();
} catch (ParseException e) {
    e.printStackTrace();
}

然后,经过一些操作,将mm:ss.SSS从长处取回:

And, after some manipulation, get mm:ss.SSS back from long:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss.SSS");
return simpleDateFormat.format(new Date(time));

如何将旧样式代码更改为Java8? 我看过LocalDateTimeInstant类,但是不知道如何正确使用它们.

How to change my old style code to Java8? I looked at LocalDateTime and Instant classes, but don't know how to use them properly.

推荐答案

您可以创建

You can create DateTimeFormatter with input formatted date and then convert into Instant with zone to extract epoch timestamp

String date = "2019-12-13_09:23:23.333";
DateTimeFormatter formatter = 
         DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss.SSS");

long mills = LocalDateTime.parse(date,formatter)
                .atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli();

System.out.println(mills);

这篇关于如何使用LocalDateTime从Java 8中的String创建以毫秒为单位的长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆