1

I want to format a date from Sun Apr 10 07:05:45 MDT 2017 to 2017-04-10T07:05:45.24Z.

I am using the following:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE-LLL-dd H:mm:sszuuuu");
formatter.parse(date);

date is in the format given above.
But I am getting a parse error at index 3

Vic
  • 99
  • 2
  • 11
  • Try to avoid such troublesome formats in the first place if at all possible. Avoid using the 3-4 letter pseudo time zone abbreviations such as `MDT` or `EST` or `IST` as they are *not* true time zones, not standardized, and not even unique(!). Specify a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_zones_by_name) in the format of `continent/region`, such as [`America/Montreal`](https://en.wikipedia.org/wiki/America/Montreal), [`Africa/Casablanca`](https://en.wikipedia.org/wiki/Africa/Casablanca), or `America/Denver`. – Basil Bourque Apr 16 '17 at 08:12

2 Answers2

1

There are multiple issues. The correct pattern is "EEE MMM dd HH:mm:ss z uuuu"

  • need to use M instead of L - I'm investigating why at the moment. See DateTimeFormatter month pattern letter "L" fails. If you do a .format("LLL") it returns 4, as in 4th month.
  • need to use spaces instead of -
  • need spaces between s, z and uuuu
  • need to use HH not H
  • April 10th was a Monday, not a Sunday

See this example code run live at IdeOne.com.

String input = "Mon Apr 10 07:05:45 MDT 2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2017-04-10T07:05:45-06:00[America/Denver]

Community
  • 1
  • 1
Adam
  • 35,919
  • 9
  • 100
  • 137
  • Okay, here is what I changed: new date is `Fri Apr 07 08:21:19 MDT 2017` and adjusted the formatter to be `"EEE MM dd HH:mm:ss z uuuu"` – Vic Apr 14 '17 at 15:29
  • One more tip: Always specify a `Locale`. Used to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such. – Basil Bourque Apr 16 '17 at 08:14
0

What's "L"? Try "MMM" for month abbrev:

DateTimeFormatter formatter = DateTimeFormatter
  .ofPattern("EEE-MMM-dd H:mm:sszuuuu");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • From the DateTimeFormatter documentation: M/L month-of-year number/text 7; 07; Jul; July; J . But I tried MMM and still getting the parse error – Vic Apr 14 '17 at 15:08