問題描述
從一種時間格式轉換為另一種時間格式 (Converting from one time format to the other)
是否可以使用 Java 時間包將此日期字符串轉換
3‑6‑2017
到此格式
"Mon Mar 6 00:00:00 EST 2017"
我創建了這兩個格式化程序,但我應該使用哪個時間實例?我已經嘗試過 LocalDate、LocalDateTime 和 ZonedDateTime。
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("M‑d‑uuuu");
DateTimeFormatter convertedToFormat = DateTimeFormatter.ofPattern("EEE MMM dd hh:mm:ss zzz yyyy");
參考解法
方法 1:
I believe that you have three issues:
- To accept month in either 1 or 2 digits (like 3 for March and 11 for November) you need to specify one pattern letter
M
, not two. Similarly for day of month. So your input format pattern string should beM‑d‑uuuu
(or justM‑d‑u
). Edit: You also needd
instead ofdd
in the “converted to” pattern. - To print hour of day (from 00 through 23) you need uppercase
HH
. Lowercasehh
is for clock hour within AM or PM from 01 through 12. - Since your input string did not contain time of day, you need to specify time of day some other way. Similar for time zone since your “converted to” format contains
zzz
for time zone abbreviation.
So in code I suggest:
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("M‑d‑uuuu");
DateTimeFormatter convertedToFormat = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy");
String input = "3‑6‑2017";
ZonedDateTime startOfDay = LocalDate.parse(input, inputFormat)
.atStartOfDay(ZoneId.of("America/New_York"));
String output = startOfDay.format(convertedToFormat);
System.out.println(output);
Output from my snippet is the desired:
Mon Mar 6 00:00:00 EST 2017
Or to answer your question a little more directly:
… which time instance should I use?
You need two of them: LocalDate
for parsing your input and ZonedDateTime
for formatting your output. And then a conversion between the two. The one‑arg atStartOfDay
method provides the conversion we need. (There is a trick for parsing directly into a ZonedDateTime
using default values for time and time zone, but it’s more complicated.)
There are other time zones that will also produce EST
as time zone abbreviation. Since your profile says you’re in Boston, I think that America/New_York is the one you want.
(by AfternoonTiger、Ole V.V.)