Trying to support Javascript's new Date().toString()
output format with Java's DateTimeFormatter
but can't seem to make it work.
Js output is of the following nature:
- Wed Apr 04 2018 09:56:16 GMT-0500 (SA Pacific Standard Time)
- Wed Apr 04 2018 16:12:41 GMT+0200 (CEST)
My current formatter:
int defaultOffset = ZonedDateTime.now().getOffset().getTotalSeconds();
DateTimeFormatter dtfJs = new DateTimeFormatterBuilder()
.appendPattern("EE MMM dd yyyy HH:mm:ss [OOOO (zzzz)]")
.parseDefaulting(ChronoField.OFFSET_SECONDS,defaultOffset
.toFormatter();
If i .parse()
those date strings from js, I get the following error:
[date] could not be parse at index 25
Index 25 for both the dates mentioned is:
- GMT-0500 (SA Pacific Standard Time)
- GMT+0200 (CEST)
I know the problem is with the : (colon) because if I print the current date with dtfJs
, I get:
Wed Apr 04 2018 10:25:10 GMT-05:00 (Colombia Time)
So the part of the GMT-05:00
is exected as GMT-0500
in the string recieved but I can't find a reserved pattern letter which matches this.
The docs say:
Offset O: This formats the localized offset based on the number of pattern letters. One letter outputs the short form of the localized offset, which is localized offset text, such as 'GMT', with hour without leading zero, optional 2-digit minute and second if non-zero, and colon, for example 'GMT+8'. Four letters outputs the full form, which is localized offset text, such as 'GMT, with 2-digit hour and minute field, optional second field if non-zero, and colon, for example 'GMT+08:00'. Any other count of letters throws IllegalArgumentException.
Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs
the hour and minute, without a colon, such as '+0130'. The output will be '+0000' when the offset is zero. Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero. Five letters outputs the hour, minute, with optional second if non-zero, with colon. It outputs 'Z' if the offset is zero. Six or more letters throws IllegalArgumentException.
Which means that the four letter will output always with colon ":", thus throwing DateTimeParseException
Help greatly appreciated, thanks
Edit
Thanks to @mszymborski I managed to pass on to validate the parenthesis part "(CEST)", what would be useful here ?
I tried with EE MMM dd yyyy HH:mm:ss 'GMT'Z (zz)
but this only works with the second date in the list, not the first
- GMT-0500 (SA Pacific Standard Time) ERROR
- GMT+0200 (CEST) PASS