smali

smali

пятница, 23 сентября 2016 г.

JodaTime goodies – flexible parsing


https://edgblog.wordpress.com/2014/02/17/jodatime-goodies-flexible-parsing/

JodaTime goodies – flexible parsing

Parsing dates in Java with JodaTime is easy.
1. instantiate a date time formatter
1
2
DateTimeFormatter dateTimeFormatter =
DateTimeFormat.forPattern("yyyyMMddHH:mm:ss.SSS") ;


2. …and parse the date time
1
dateTimeFormatter.parseDateTime("20120515 09:30:25.123") ;

3. but when  the date time format changes (say to include a timezone)…alarm bells.
1
2
3
4
dateTimeFormatter.parseDateTime("20120515 09:30:25.123 +0000") ;
//results in//
java.lang.IllegalArgumentException:
Invalid format: "20120515 09:30:25.123 +0000" is malformed at " +0000"

4. Fortunately the JodaTime api includes a DateTimeFormatterBuilder which can be used to build a dateTimeFormatter customised with multiple printers and parsers.
1
2
3
4
5
6
7
8
9
10
11
DateTimeFormatter dateTimeFormatter=
DateTimeFormat.forPattern("yyyyMMddHH:mm:ss.SSS") ;
 
DateTimeFormatter dateTimeFormatterWithTimeZone=
DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss.SSS Z");
 
DateTimeFormatter optionalTimeZoneFormatter=
new DateTimeFormatterBuilder()
 .append(null, //because no printing is required
 new DateTimeParser[]{dateTimeFormatter.getParser(),
dateTimeFormatterWithTimeZone.getParser()}).toFormatter();

5. now the same DateTimeFormatter handles different date time formats
1
2
optionalTimeZoneFormatter.parseDateTime("20120515 09:30:25.123") ;
optionalTimeZoneFormatter.parseDateTime("20120515 09:30:25.123 +0000") ;

Комментариев нет:

Отправить комментарий