我正在学习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:30PM、10:30 PM、10:30pm、10:30 pm、10:30p、10:30 p 等格式输入时间,所有这些条目都导致抛出异常错误,我遇到这样的错误
Exception in thread "main" java.time.format.DateTimeParseException: Text '10:30 pm' could not be parsed at index 6
知道我可能做错了什么吗?谢谢!
由于用户输入的内容仅代表时间,因此您需要将其解析为当地时间 https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html,另一个错误是你使用了错误的模式,H
是一天中的某个时间 (0-23);你需要h
in 日期时间格式化程序 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
LocalTime localTime = LocalTime.parse("10:30 PM",formatter);
将输入解析后LocalTime https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalTime.html你可以把它转换成分区日期时间 https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html。但您必须指定一个日期(LocalDate https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/LocalDate.html)以及时间和区域。您在问题中的代码只有一天中的时间,并且缺少实例化所需的日期和区域ZonedDateTime
.
ZonedDateTime dateTime = localTime.atDate(LocalDate.now()).atZone(ZoneId.systemDefault());
然后你可以使用将其转换为另一个区域withZoneSameInstant https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant-java.time.ZoneId-
ZonedDateTime result = dateTime.withZoneSameInstant(ZoneId.of("America/New_York));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)