| Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
| DateParser |
|
| 3.3333333333333335;3.333 |
| 1 | package org.codeforamerica.open311.internals.parsing; | |
| 2 | ||
| 3 | import java.util.Date; | |
| 4 | ||
| 5 | import org.joda.time.DateTime; | |
| 6 | import org.joda.time.DateTimeZone; | |
| 7 | import org.joda.time.format.DateTimeFormat; | |
| 8 | import org.joda.time.format.DateTimeFormatter; | |
| 9 | import org.joda.time.format.ISODateTimeFormat; | |
| 10 | ||
| 11 | /** | |
| 12 | * Provides operations to handle dates. Check the <a | |
| 13 | * href="http://wiki.open311.org/GeoReport_v2#Date.2Ftime_format">GeoReport | |
| 14 | * wiki</a> for more information. | |
| 15 | * | |
| 16 | * @author Santiago MunĂn <santimunin@gmail.com> | |
| 17 | * | |
| 18 | */ | |
| 19 | 39 | public class DateParser { |
| 20 | ||
| 21 | /** | |
| 22 | * List of possible formats sorted by preference. | |
| 23 | */ | |
| 24 | 39 | private DateTimeFormatter[] dateFormats = { |
| 25 | ISODateTimeFormat.dateTimeNoMillis(), | |
| 26 | DateTimeFormat.forPattern("YYYY-MM-DD HH:mm") }; | |
| 27 | ||
| 28 | /** | |
| 29 | * Sets the timezone of the system. | |
| 30 | * | |
| 31 | * @param timeZone | |
| 32 | * A valid timezone. | |
| 33 | */ | |
| 34 | public DateParser withTimezone(DateTimeZone timeZone) { | |
| 35 | 3 | for (int i = 0; i < dateFormats.length; i++) { |
| 36 | 2 | dateFormats[i] = dateFormats[i].withZone(timeZone); |
| 37 | } | |
| 38 | 1 | return this; |
| 39 | } | |
| 40 | ||
| 41 | /** | |
| 42 | * Parses a string representing a date. | |
| 43 | * | |
| 44 | * @param rawDate | |
| 45 | * ISO 8601 is the preferred format. Check | |
| 46 | * <code>dateFormats</code> to check all the accepted formats. | |
| 47 | * @return A date object. | |
| 48 | */ | |
| 49 | public Date parseDate(String rawDate) { | |
| 50 | 86 | for (int i = 0; i < dateFormats.length; i++) { |
| 51 | try { | |
| 52 | 85 | return dateFormats[i].parseDateTime(rawDate).toDate(); |
| 53 | 3 | } catch (Exception e) { |
| 54 | } | |
| 55 | } | |
| 56 | 1 | return null; |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * Prints a date. ISO 8601 is the preferred format. Check | |
| 61 | * <code>dateFormats</code> to check all the accepted formats. | |
| 62 | * | |
| 63 | * @param date | |
| 64 | * Date to print. | |
| 65 | * @return ISO 8601 format date if possible (else, the first valid) or | |
| 66 | * <code>null</code> if it didn't match any format. | |
| 67 | */ | |
| 68 | public String printDate(Date date) { | |
| 69 | 26 | for (int i = 0; i < dateFormats.length; i++) { |
| 70 | try { | |
| 71 | 26 | return dateFormats[i].print(new DateTime(date)); |
| 72 | 0 | } catch (Exception e) { |
| 73 | } | |
| 74 | } | |
| 75 | 0 | return null; |
| 76 | } | |
| 77 | } |