David Green
David Green

Reputation: 1234

Java Parsing Date and Time with SimpleDateFormat

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.

Upvotes: 1

Views: 55

Answers (1)

azro
azro

Reputation: 54148

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

Upvotes: 1

Related Questions