简体   繁体   English

无法从 HH:mm:ss.SSS'Z' 转换为 HH:MM 格式的 Java

[英]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.

相关问题 POI-以HH:MM:SS.sss格式处理数据 - POI - Handling data in HH:MM:SS.sss Format 测试时间格式HH:MM:SS.sss - Test the time format HH:MM:SS.sss 如何将 HH:mm:ss.SSS 转换为毫秒? - How to convert HH:mm:ss.SSS to milliseconds? 如何将时间戳从yyyy-MM-ddThh:mm:ss:SSSZ格式转换为MM / dd / yyyy hh:mm:ss.SSS格式?从ISO8601到UTC - How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC 如何在 Java 中以 hh:mm:ss.SSS 格式格式化经过的时间间隔? - How to format an elapsed time interval in hh:mm:ss.SSS format in Java? Gson中的DateFormat模式“yyyy-MM-dd'T'HH:mm:ss.SSS'Z'” - DateFormat pattern “yyyy-MM-dd'T'HH:mm:ss.SSS'Z'” in Gson XMLGregorianCalendar日期格式'dd / MM / yyyy HH:mm:ss.SSS' - XMLGregorianCalendar date format 'dd/MM/yyyy HH:mm:ss.SSS' 以 yyyy-MM-dd HH:mm:ss.SSS 格式从当前 dateTime 获取 1 年前的 dateTime - Get 1 year back dateTime from current dateTime in yyyy-MM-dd HH:mm:ss.SSS format 从“yyyy-MM-dd hh:mm:ss.SSS”解析日期和时间 -------> android中的“hh:mm aa” - Parsing Date and time from "yyyy-MM-dd hh:mm:ss.SSS" -------> "hh:mm aa" in android Json反序列化“ 2017-09-11 14:28:42”失败,原因是“它似乎适合格式为“ yyyy-MM-dd'T'HH:mm:ss.SSS'Z'”” - Json Deserialization of “2017-09-11 14:28:42” fails with 'while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'''
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM