【问题标题】:ZonedDateTime.parse not working for parsing time with am or pmZonedDateTime.parse 无法使用 am 或 pm 解析时间
【发布时间】:2020-07-21 16:02:28
【问题描述】:

我正在学习 java,试图构建一个工具来根据用户输入(时间、时区 A 和时区 B 的输入)将特定时间从时区 A 转换为时区 B。这是关于工具以特定格式收集时间以将其转换为 ZonedDateTime 对象的部分。

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public static String fullTime;
public static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm a");
public static ZonedDateTime newTime;

public static void getHourAndMinutes(){
        System.out.print("Please type in the time you have in mind in format hh:mm am/pm\n");
        Scanner in = new Scanner(System.in);
        fullTime = in.nextLine();
        System.out.println(fullTime);
        newTime = ZonedDateTime.parse(fullTime, formatter);

我尝试以晚上 10:30、晚上 10:30、晚上 10:30、晚上 10:30、晚上 10:30、晚上 10:30 等格式输入时间,所有这些输入都导致异常错误抛出,我收到这样的错误

Exception in thread "main" java.time.format.DateTimeParseException: Text '10:30 pm' could not be parsed at index 6

知道我可能做错了什么吗?谢谢!

【问题讨论】:

    标签: java datetime zoneddatetime


    【解决方案1】:

    由于用户输入的输入只是代表时间,您需要将其解析为LocalTime,另一个错误是您使用了错误的模式,H 是小时数(0-23);你需要h in DateTimeFormatter

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
    
    LocalTime localTime = LocalTime.parse("10:30 PM",formatter);
    

    将输入解析为LocalTime后,您可以将其转换为ZonedDateTime。但是您必须指定日期 (LocalDate) 以及时间和区域。您在问题中的代码只有一天中的时间,并且缺少实例化 ZonedDateTime 所需的日期和区域。

    ZonedDateTime dateTime = localTime.atDate(LocalDate.now()).atZone(ZoneId.systemDefault());
    

    然后您可以使用withZoneSameInstant将其转换为另一个区域

    ZonedDateTime result = dateTime.withZoneSameInstant(ZoneId.of("America/New_York));
    

    【讨论】:

    • 谢谢,这正是我错过的。误用 ZonedDateTime.parse 作为我的时间字符串。
    【解决方案2】:

    知道我可能做错了什么吗?谢谢!

    恐怕有很多事情。

    1. 对于ZonedDateTime,您需要一个日期、一个时间和一个时区。要将仅包含一天中时间的字符串解析为 ZonedDateTime,您需要提供默认日期和默认时区。但是,相反,我会解析为LocalTime,如果没有日期且没有时区,这正是一个时间。解析后可以转换。您需要确定转换日期,因为您的时区 A(和 B 也是)可能在不同日期使用不同的 UTC 偏移量,因为夏令时 (DST) 和/或它们的基本 UTC 偏移量的历史和/或未来变化。
    2. 您需要为格式化程序提供区域设置,以告知它采用哪种语言假设 AM 和 PM。例如DateTimeFormatter.ofPattern("HH:mm a", Locale.ENGLISH)
    3. 您需要为您指定的区域设置以正确的大小写(大写或小写)输入 AM 或 PM。
    4. 要解析上午或下午从 01 到 12 的小时字符串,您需要在格式模式字符串中使用小写 hh。不是大写的 HH,表示一天中从 00 到 23 的小时。

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多