如何将给定时间(字符串)转换为LocalTime? [英] How to convert a given time (String) to a LocalTime?

查看:2302
本文介绍了如何将给定时间(字符串)转换为LocalTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将要求用户输入特定时间:10 AM、12:30 PM、2:47 PM、1:09 AM、5PM等. 我将使用Scanner来获取用户的输入.

I will be asking a user to enter a specific time: 10AM, 12:30PM, 2:47PM, 1:09AM, 5PM, etc. I will be using a Scanner to get the user's input.

如何将String解析/转换为LocalTime对象? Java中是否有任何内置函数可以使我做到这一点?

How can I parse/convert that String to a LocalTime object? Is there any built-in function in Java that will allow me to do that?

推荐答案

只需使用java.time.format.DateTimeFormatter:

DateTimeFormatter parser = DateTimeFormatter.ofPattern("h[:mm]a");
LocalTime localTime = LocalTime.parse("10AM", parser);

解释模式:

  • h:一天中的上午/下午(从1到12),用1或2位数字
  • []:可选节的定界符(其中的所有内容都是可选的)
  • :mm:一个:字符,后跟两位数字的分钟数
  • a:AM/PM的代号
  • h: am/pm hour of day (from 1 to 12), with 1 or 2 digits
  • []: delimiters for optional section (everything inside it is optional)
  • :mm: a : character followed by minutes with 2 digits
  • a: designator for AM/PM

这适用于您的所有输入.

This works for all your inputs.

这篇关于如何将给定时间(字符串)转换为LocalTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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