Java DateTimeFormatter for time zone with an optional colon separator?

Nelson G. picture Nelson G. · Jan 6, 2016 · Viewed 19k times · Source

I'm trying to build a DateTimeFormatter that can accepts offset with colon or offset without colon.

Is there a way to pass this test :

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[X]");
dateTimeFormatter.parse("2015-01-28T10:21:44+0100"); // OK
dateTimeFormatter.parse("2015-01-28T10:21:44+01:00"); // KO

Answer

Titus picture Titus · Jan 6, 2016

This: yyyy-MM-dd'T'HH:mm:ss[XXX][X] seems to work.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[XXX][X]");
dateTimeFormatter.parse("2015-01-28T10:21:44+0100");
dateTimeFormatter.parse("2015-01-28T10:21:44+01:00");