Reputation: 397
Is it possible to convert this date string using Java time package
3-6-2017
to this format
"Mon Mar 6 00:00:00 EST 2017"
I created these two formatters, but which time instance should I use? I've tried LocalDate, LocalDateTime, and ZonedDateTime.
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("M-d-uuuu");
DateTimeFormatter convertedToFormat = DateTimeFormatter.ofPattern("EEE MMM dd hh:mm:ss zzz yyyy");
Upvotes: 0
Views: 51
Reputation: 86379
I believe that you have three issues:
M
, not two. Similarly for day of month. So your input format pattern string should be M-d-uuuu
(or just M-d-u
). Edit: You also need d
instead of dd
in the “converted to” pattern.HH
. Lowercase hh
is for clock hour within AM or PM from 01 through 12.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.
Upvotes: 4