【问题标题】:Java Instant to LocalDateTime trailing zeroJava Instant 到 LocalDateTime 尾随零
【发布时间】:2018-11-15 07:43:02
【问题描述】:

我使用 Spring Boot 在 Java 中将 Instant 转换为 LocalDateTime,如下所示

LocalDateTime.ofInstant(timeInUtc, zoneId);

在我的测试中,我得到了一个正则表达式来检查我的资源是否返回一个带有 LocalDateTime 的 Json。正则表达式需要一个 JSON 值,格式为:

 2018-11-15T08:38:49.382

但看起来后面的零被删除了,意思是而不是

2018-11-15T08:38:49.380

这符合正则表达式,我明白了

 2018-11-15T08:38:49.38

如何确保不删除尾随零?

【问题讨论】:

  • 如何将 localdatetime 对象转换为字符串?
  • 如何打印/格式化它?如果我运行System.out.println(LocalDateTime.parse("2018-11-15T08:38:49.380")),我会得到2018-11-15T08:38:49.380(尾随零)。
  • 我使用 Jackson 将我的对象序列化和反序列化为 JSON。
  • 为了精确起见,不会删除尾随零。 InstantLocalDateTime 都没有任何文本表示,但是当您调用 toString 时会生成一个。在这种情况下不会生成尾随零。它们确实会生成 ISO 8601 格式,这在大多数情况下都很好,所以请再次检查在您的情况下是否真的存在零的问题。
  • 你为什么不改正则表达式?

标签: java spring-boot java-8 instant


【解决方案1】:

格式化日期将有助于保留尾随零

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")

输出如下:

2018-11-15T08:03:45.580

以下代码:

public class Post2 {

    public static void main(String[] args) {

        String date = LocalDateTime.ofInstant(Instant.now(), ZoneId.of("UTC"))
           .format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));
        System.out.println(date);

    }
}

编辑 添加正则表达式匹配以匹配带有和不带有毫秒的日期时间。

        String regex = "^\\d\\d\\d\\d-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01]) (00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])(\\.{0,1}[0-9]{1,3})$";

        String str1 = "2015-1-11 13:57:24";

        String str2 = "2015-1-11 13:57:24.0";
        String str3 = "2015-1-11 13:57:24.00";
        String str4 = "2015-1-11 13:57:24.000";
        String str5 = "2015-1-11 13:57:24.1";
        String str6 = "2015-1-11 13:57:24.12";
        String str7 = "2015-1-11 13:57:24.1222";
        String str8 = "2015-1-11 13:57:24.02";

        System.out.println( str1.matches(regex));
        System.out.println(str2.matches(regex));
        System.out.println(str3.matches(regex));
        System.out.println(str4.matches(regex));
        System.out.println(str5.matches(regex));
        System.out.println(str6.matches(regex));
        System.out.println(str7.matches(regex));
        System.out.println(str8.matches(regex));

输出:

true
true
true
true
true
true
false
true

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2017-12-29
    • 2020-06-22
    • 2020-07-27
    • 2017-11-18
    • 2011-10-27
    相关资源
    最近更新 更多