AfternoonTiger
AfternoonTiger

Reputation: 397

Converting from one time format to the other

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

Answers (1)

Anonymous
Anonymous

Reputation: 86379

I believe that you have three issues:

  1. 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 be M-d-uuuu (or just M-d-u). Edit: You also need d instead of dd in the “converted to” pattern.
  2. To print hour of day (from 00 through 23) you need uppercase HH. Lowercase hh is for clock hour within AM or PM from 01 through 12.
  3. 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.

Upvotes: 4

Related Questions