3

I would like to parse an GMT-date like Wed, 21 Oct 2016 07:28:00 GMTwith DateTimeFormatter into an Instant. To create the pattern i used the official documentation: DateTimeFormatter

My code so far:

String date = "Wed, 21 Oct 2016 07:28:00 GMT";

DateTimeFormatter gmtFormat = DateTimeFormatter.ofPattern("EEE' dd LLL yyyy HH:mm:ss '''");
TemporalAccessor parsed = gmtFormat.parse(date);
Instant a = Instant.from(parsed);

System.out.println(a);

But every time i've got this error:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Wed, 21 Oct 2016 07:28:00 GMT' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)

At index 0 is Wed, I used EEE which represents day-of-week by definition, there are also examples which represent: Tue; Tuesday; T.

I've also tried lower-, and uppercase but not successfully. What is wrong? Did I overlook something?

3
  • 4
    Why not just use RFC_1123_DATE_TIME format? Commented Mar 30, 2018 at 18:55
  • Try outputting gmtFormat.format(Instant.now()) to see if you really get what you expect. Can there be any localization involved? Commented Mar 30, 2018 at 18:58
  • @BobJacobsen i've got this error: Unsupported field: DayOfWeek Commented Mar 30, 2018 at 19:00

3 Answers 3

5

It works with the code

String date = "Fri, 21 Oct 2016 07:28:00 GMT";

DateTimeFormatter gmtFormat = DateTimeFormatter.RFC_1123_DATE_TIME;
TemporalAccessor parsed = gmtFormat.parse(date);
Instant a = Instant.from(parsed);

System.out.println(a);

But you have to change the day because otherwise it doesn't fit to the given date.

Sign up to request clarification or add additional context in comments.

Comments

0

EEE is the proper format for Wed. But it does not include the comma.

Try this:

DateTimeFormatter gmtFormat = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss '''"); 

Useful link

4 Comments

Didn't i excluded it by using '?
@SimonW. Not sure really. I usually write explicitlly the intermediate characters if present. Check this link, It may help fileformat.info/tip/java/simpledateformat.htm
Also what about LLL? I think the month name flag is MMM
MM is the numeric form "10" and LLL is the text form "Oct". docs.oracle.com/javase/8/docs/api/java/time/format/…
0

You're asking for redundant information: The day of the week and the date.

Change the format to just ignore the first three characters, leaving it reading the day/month/year.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.