[英]Java Instant to LocalDateTime trailing zero
I converted an Instant to LocalDateTime in Java with Spring Boot as seen below我使用 Spring Boot 在 Java 中将 Instant 转换为 LocalDateTime,如下所示
LocalDateTime.ofInstant(timeInUtc, zoneId);
In my test I got a Regex to check whether my resource returns a Json with a LocalDateTime.在我的测试中,我得到了一个 Regex 来检查我的资源是否返回带有 LocalDateTime 的 Json。 The Regex expects a JSON value in the format:正则表达式需要以下格式的 JSON 值:
2018-11-15T08:38:49.382
But it looks like the trailing zero is removed, meaning instead of但看起来尾随零已被删除,这意味着而不是
2018-11-15T08:38:49.380
which would comply to the regex, I get这将符合正则表达式,我得到
2018-11-15T08:38:49.38
How can I make sure that the trailing zero is not removed?如何确保不删除尾随零?
Formatting the date would help to retain the trailing zero格式化日期将有助于保留尾随零
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
Output looks like below:输出如下所示:
2018-11-15T08:03:45.580 2018-11-15T08:03:45.580
The code below:下面的代码:
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);
}
}
EDIT Adding regex matching to match date time with and without milli seconds.编辑添加正则表达式匹配以匹配带和不带毫秒的日期时间。
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));
output:输出:
true
true
true
true
true
true
false
true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.