如何在Java中使用两个或三个毫秒的数字来解析日期时间? [英] How to parse date-time with two or three milliseconds digits in java?

查看:96
本文介绍了如何在Java中使用两个或三个毫秒的数字来解析日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我将String解析为 LocalDateTime 的方法.

 公共静态字符串formatDate(最终字符串日期){DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");LocalDateTime formatDateTime = LocalDateTime.parse(date,formatter);返回formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();} 

但这仅适用于输入字符串,例如 2017-11-21 18:11:14.05 但对于 2017-11-21 18:11:14.057 失败与 DateTimeParseException .

如何定义同时适用于 .SS .SSS 的格式化程序?

解决方案

tl; dr

完全不需要定义格式化程序.

  LocalDateTime.parse("2017-11-21 18:11:14.05" .replace(","T")) 

ISO 8601

Sleiman Jneidi的

Here is my method to parse String into LocalDateTime.

    public static String formatDate(final String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");
        LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
        return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
    }

but this only works for input String like 2017-11-21 18:11:14.05 but fails for 2017-11-21 18:11:14.057 with DateTimeParseException.

How can I define a formatter that works for both .SS and .SSS?

解决方案

tl;dr

No need to define a formatter at all.

LocalDateTime.parse(
    "2017-11-21 18:11:14.05".replace( " " , "T" )
)

ISO 8601

The Answer by Sleiman Jneidi is especially clever and high-tech, but there is a simpler way.

Adjust your input string to comply with ISO 8601 format, the format used by default in the java.time classes. So no need to specify a formatting pattern at all. The default formatter can handle any number of decimal digits between zero (whole seconds) and nine (nanoseconds) for the fractional second.

Your input is nearly compliant. Just replace the SPACE in the middle with aT.

String input = "2017-11-21 18:11:14.05".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );

ldt.toString(): 2017-11-21T18:11:14.050


这篇关于如何在Java中使用两个或三个毫秒的数字来解析日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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