Java字符串到日期的转换问题-毫秒转换不正确

问题描述 投票:0回答:1

[将String转换为日期时遇到的问题。

代码:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS");
String date = "2019-12-10-11.48.57.816687";
System.out.println(dateFormat.parse(date));

预期输出:

Tue Dec 10 11:48:57.816687 CET 2019

实际输出:

Tue Dec 10 12:02:33 CET 2019
java date
1个回答
0
投票

除非您必须使用Java 5及以下版本,否则不再使用java.util进行日期时间操作...

现在有java.time,使您可以执行此操作:

public static void main(String[] args) {
    // the source String
    String date = "2019-12-10-11.48.57.816687";
    // parse it to a LocalDateTime using the specified format
    LocalDateTime localDateTime = LocalDateTime.parse(date, 
            DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS"));
    // print it in a standardized format
    System.out.println(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}

及其输出为

2019-12-10T11:48:57.816687

如果需要,可以使用不同的格式。

© www.soinside.com 2019 - 2024. All rights reserved.