如何使用 LocalDateTime 从 Java 8 中的字符串创建以毫秒为单位的长时间?

How to create a long time in Milliseconds from String in Java 8 with LocalDateTime?

我有一个格式为 yyyy-MM-dd_HH:mm:ss.SSS 的输入日期,并以这种方式将其转换为长格式:

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();
}

然后,经过一些操作,从 long:

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

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

您可以使用区域创建 DateTimeFormatter with input formatted date and then convert into Instant 以提取纪元时间戳

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);

tl;博士

LocalDateTime
.parse(
    "2019-12-13_09:23:23.333".replace( "_" , "T" )
)
.atZone(
    ZoneId.of( "Africa/Casablanca" ) 
)
.toInstant()
.toEpochMilli() 

ISO 8601

您输入的字符串几乎符合 java.time 类 中默认使用的标准 ISO 8601 格式,当 parsing/generating 字符串.

完全符合,简单替换下划线_ I.中间用大写T.

String input =  "2019-12-13_09:23:23.333".replace( "_" , "T" ) ;

无需格式化程序即可解析。

LocalDateTime ldt = LocalDateTime.parse( input ) ;

指定用于此日期和时间的时区。该数据的发布者是指该日期的日本东京上午 9 点,还是他们指的是美国俄亥俄州托莱多的上午 9 点?那将是相隔几个小时的两个不同时刻。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

提取一个 Instant 以调整为 UTC。在 UTC 中查询自 1970 年第一刻以来的毫秒数。

long milliseconds = zdt.toInstant().toEpochMilli() ;