ZonedDateTime.parse无法用于解析上午或下午的时间 [英] ZonedDateTime.parse not working for parsing time with am or pm

查看:207
本文介绍了ZonedDateTime.parse无法用于解析上午或下午的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning java, trying to build a tool to convert a specific time from timezone A to timezone B based on user input (input of the time, timezone A, and timezone B). This is about the part where the tool gathers a time in a specific format to convert it into a ZonedDateTime object.

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 PM、10:30 PM,10:30 pm、10:30 pm,10:30p,10:30 p这样的格式输入时间,所有这些条目均导致异常错误抛出,我遇到这样的错误

I have tried to enter the time in formats like 10:30PM, 10:30 PM, 10:30pm, 10:30 pm, 10:30p, 10:30 p, all of these entries has caused exception error to be thrown, I'm getting errors like this one

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

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

Any idea what I might be doing wrong? Thanks!

推荐答案

由于用户输入的内容仅代表时间,因此您需要将其解析为 DateTimeFormatter h >

Since the user entering input is just representing time you need to parse it into LocalTime, and the other mistake is you are using the wrong pattern, H is hour-of-day (0-23); you need h in DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");

LocalTime localTime = LocalTime.parse("10:30 PM",formatter);

将输入解析为

After parsing the input into LocalTime you can convert it into ZonedDateTime. But you must specify a date (LocalDate) as well as the time and the zone. Your code in the Question had only the time-of-day, and lacked the date and zone needed to instantiate a ZonedDateTime.

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

然后,您可以使用

这篇关于ZonedDateTime.parse无法用于解析上午或下午的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆