簡體   English   中英

Java Instant 到 LocalDateTime 尾隨零

[英]Java Instant to LocalDateTime trailing zero

我使用 Spring Boot 在 Java 中將 Instant 轉換為 LocalDateTime,如下所示

LocalDateTime.ofInstant(timeInUtc, zoneId);

在我的測試中,我得到了一個 Regex 來檢查我的資源是否返回帶有 LocalDateTime 的 Json。 正則表達式需要以下格式的 JSON 值:

 2018-11-15T08:38:49.382

但看起來尾隨零已被刪除,這意味着而不是

2018-11-15T08:38:49.380

這將符合正則表達式,我得到

 2018-11-15T08:38:49.38

如何確保不刪除尾隨零?

格式化日期將有助於保留尾隨零

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM