1

I have this input:

Thu May 31 01:43:45 GMT-8 2018

These are the most recent patterns I have tried:

"EEE MMM dd HH:mm:ss zX yyyy"
"EEE MMM dd HH:mm:ss 'GMT'X yyyy"
"EEE MMM dd HH:mm:ss zX yyyy"

I get an unparseable date exception thrown when I try parsing the input using the patterns. I have tried several patterns but can't figure out how to match the GMT offset portion of the input. I can do this with regular expressions - I don't really need the offset but would rather figure out what pattern to use. Of course the offset could also be a 2-digit offset if it's more than 9 hours from GMT.

I've looked at the SimpleDateformat documentation and several examples here and other places but can't figure out the correct pattern I need.

2
  • Suggestion -- try taking a new Date object and call format() using the SimpleDateFormats that you have listed above, and see what the output from each looks like. It might point you in the right direction. Commented May 30, 2018 at 18:54
  • @ElliottFrisch Yes it is O match GMT-8 Commented May 30, 2018 at 19:03

1 Answer 1

1

Using LocalDateTime API from Java8 (more recent and easier to use than Date), you can use the ZonedDateTime version::

  • to match the day use one E only
  • to mach the GMT-8 use 0 (fifth block, third lines in the letters in the link below)
  • I add Locale.ENGLISH because I'm on a french configuration, not sure you need to add it on english config

★ DateTimeFormatter Documentation

String str = "Thu May 31 01:43:45 GMT-8 2018";

DateTimeFormatter formatter = 
                  DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss O yyyy", Locale.ENGLISH);

ZonedDateTime date = ZonedDateTime.parse(str, formatter);
System.out.println(date.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); 
// 2018-05-31T01:43:45-08:00

★ Working example

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

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.