use*_*180 4 java java-time localdatetime datetimeformatter java.time.localdatetime
我有以下格式的日期:1/1/2020 3:4:7 AM我正在尝试使用DateTimeFormatter.
我有以下带有格式化程序的代码来解析它,但它不起作用。
LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM", DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"));
Run Code Online (Sandbox Code Playgroud)
我收到以下异常:
java.time.format.DateTimeParseException: Text '1/1/2020 3:4:7 AM' could not be parsed at index 0
谁能帮我?
Two separate problems:
You're using e.g. MM which is an explicit: Always the full amount of digits, zero-padded. Your string is not like that, it's just the number. So, make that M/d/uuuu h:m:s a.
EDIT: Changed yyyy to uuuu, thanks, @deHaar. Reasoning: yyyy or uuuu rarely matters, but note that this mean 4 digits are required. The difference kicks in for years before 0: uuuu goes negative, yyyy does not and expects you to use e.g. GG so that you get 44 BC instead of -44. In that way, uuuu is just more correct, even though usually the difference is not going to come up.
The second problem is that you should pretty much never use this version of ofPattern - it has a bug, which you can't catch with unit tests, which makes that a bug that is thousands of times 'heavier', and thus, a real problem.
You need to specify locale. Without it, 'AM' is not going to parse unless your platform default locale is english.
LocalDateTime date = LocalDateTime.parse("1/1/2020 3:4:7 AM",
DateTimeFormatter.ofPattern("M/d/uuuu h:m:s a", Locale.ENGLISH));
Run Code Online (Sandbox Code Playgroud)
works great.
| 归档时间: |
|
| 查看次数: |
477 次 |
| 最近记录: |