Joda's time - analysis when the format changes

I am getting date / time strings from a website that seems to have a variable number of digits for a millisecond value.

Example:

2013-08-15T06: 21: 49,35054 + 01: 00

2013-08-15T06: 21: 49,350546 + 01: 00

2013-08-15T06: 21: 49 + 01: 00

I am currently using:

static final Map<Integer,DateTimeFormatter> parsers = new HashMap<Integer,DateTimeFormatter>(); static { parsers.put("2013-07-23T22:44:00+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")); parsers.put("2013-07-27T18:00:59.9+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SZ")); parsers.put("2013-07-27T18:00:59.99+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSZ")); parsers.put("2013-07-27T18:00:59.999+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); parsers.put("2013-07-27T18:00:59.9999+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSZ")); parsers.put("2013-07-27T18:00:59.99999+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSZ")); parsers.put("2013-07-27T18:00:59.999999+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ")); parsers.put("2013-07-27T18:00:59.9999999+01:00".length(), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ")); } public static Date parseDate(String date) { return parsers.get(date.length()).parseDateTime(date).toDate(); } 

Is there a more convenient way to do this?

+4
source share
3 answers

I found a solution to my specific problem with a variable number of digits in the ms field.

 static final DateTimeFormatter isoParser = ISODateTimeFormat.dateTimeParser(); public static Date parseDate(String date) { return isoParser.parseDateTime(date).toDate(); } 

However - I would be interested in a more general solution that can handle any of several possible but distinct formats.

+1
source

Why not separate the + character and add the remaining decimal places? eg. the change

 2013-08-15T06:21:49.35054 

to

 2013-08-15T06:21:49.350540 

and then just use one DateTimeFormat

0
source

I would prefer to use this method since you are dealing with ISO-8601

 public static Date getDateFromIsoISO8601(String str) { try { return ISO8601Utils.parse(str, new ParsePosition(0)); } catch (Exception e) { Log.e("Parsing","error:getDateFromIsoISO8601: " + e.getMessage()); return null; } } 

Use joda-time

0
source

Source: https://habr.com/ru/post/1497199/


All Articles