将字符串转换为特定格式的DateTime对象(例如,不包含日期)。

huangapple go评论72阅读模式
英文:

Convert String to DateTime object in specific format(ex. without Date)

问题

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
LocalTime time = LocalTime.parse(str, formatter);
英文:

I need to convert my String to time without the date. I used SimpleDateFormat and it worked. But what I need is from Localdatetime in java.

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

But it is giving me this error:

> Exception in thread "main" java.time.format.DateTimeParseException: Text '10:30:20 PM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 22:30:20 of type java.time.format.Parsed

答案1

得分: 3

你可以在 DateTimeFormatter 中使用 Locale -

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
LocalTime time = LocalTime.parse(str, formatter);
System.out.println(time);

另外请注意,在这里你必须使用 LocalTime.parse(),因为你的字符串中没有日期部分。

英文:

You could use Locale with your DateTimeFormatter -

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a",Locale.ENGLISH);
LocalTime time = LocalTime.parse(str, formatter);
System.out.println(time);

And also note you have to use LocalTime.parse() here, since your string in the date doesn't contain date part.

答案2

得分: 2

你需要的是 LocalTime 而不是 LocalDateTime。
你也可以尝试这样做:

LocalTime localTime = LocalTime.parse("10:45:30 PM", DateTimeFormatter.ofPattern("hh:mm:ss a"));
System.out.println(localTime);

如果时间使用24小时制格式:

LocalTime localTime = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime);
英文:

What you need is LocalTime & not LocalDateTime.
You can try this as well:

LocalTime localTime = LocalTime.parse("10:45:30 PM", DateTimeFormatter.ofPattern("hh:mm:ss a"));
System.out.println(localTime);

If you have time in 24 hr format:

LocalTime localTime = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime);

huangapple
  • 本文由 发表于 2020年4月9日 14:30:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61115208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定