[英]Not able to convert from HH:mm:ss.SSS'Z' to HH:MM format Java
I'm trying to convert into HH:MM format in Java我正在尝试在 Java 中转换为 HH:MM 格式
Here is my code这是我的代码
String date = "18:30:00.000Z";
try {
ZonedDateTime parsed = ZonedDateTime.parse(date);
ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.systemDefault());
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
System.out.println(fmt.format(z));
} catch(Exception e) {
e.printStackTrace();
}
Is there anything wrong in my code我的代码有什么问题吗
Here is the exception这是例外
java.time.format.DateTimeParseException: Text '18:30:00.000Z' could not be parsed at index 0
The string you are trying to parse is not a date and time, but only a time.您尝试解析的字符串不是日期和时间,而只是时间。 So the type ZonedDateTime
is not the appropriate type to use here.所以ZonedDateTime
类型不是在这里使用的合适类型。 Use OffsetTime
instead, which is a class for holding just a time (without a date).使用OffsetTime
代替,这是一个只保存时间(没有日期)的类。
String input = "18:30:00.000Z";
OffsetTime time = OffsetTime.parse(input);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
String result = formatter.format(time);
System.out.println(result);
Output:输出:
6:30 PM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.