wired00 wired00 - 6 months ago 26
Java Question

Determine which DateTimePattern pattern was used joda

If I have code such as this:

DateTimeParser[] parsers = {
DateTimeFormat.forPattern("yyyyMM").getParser(),
DateTimeFormat.forPattern("yyyyMMdd").getParser(),
DateTimeFormat.forPattern("yyyyMMddHHmm").getParser(),
DateTimeFormat.forPattern("yyyyMMddHHmmZ").getParser(),
DateTimeFormat.forPattern("yyyyMMddHHmmss.SSSSZ").getParser()
};

DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();

final DateTime dateTime = formatter
.parseDateTime(dateString);

return new Timestamp(dateTime.getMillis());


How can I determine which pattern was used? I want to force UTC timezone only in situation when no timezone is explicitly provided. ie, when Z is missing

Alternatively, how can I simply determine if a timezone was provided when parsing a joda datetime?

Answer

You can always get the zone from the code below with withOffsetParsed() and compare with your default zone

String dateString = "2016052914346.2354+0300";
DateTimeParser[] parsers = {DateTimeFormat.forPattern("yyyyMM").getParser(),DateTimeFormat.forPattern("yyyyMMddHHmmss.SSSSZ").getParser()};
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
DateTime dateTime = formatter.withOffsetParsed().parseDateTime(dateString);
DateTimeZone zone = dateTime.getZone();//+03.00
Comments