How to create a common date format in java for Solr?

I have a requirement when a date can be transferred in the following formats before indexing them in Solr. Below are examples of dates.   

String dateStr = "2012-05-23T00:00:00-0400";
String dateStr1 = "May 24, 2012 04:57:40 GMT";
String dateStr2 = "2011-06-21";
    
The standard Solr format is "yyyy-MM-dd'T'HH: mm: ss'Z '" .

I tried SimpleDateFormat, but I can not write a general program to support various formats. This throws parsing exceptions.

I also tried joda time, but has not been achieved so far in UTC conversion.   

public static String toUtcDate(final String iso8601) {
        DateTime dt = ISO_PARSE_FORMAT.parseDateTime(iso8601);
        DateTime utcDt = dt.withZone(ZONE_UTC);
        return utcDt.toString(ISO_PRINT_FORMAT);
    }

Is there a standard library for this?

Any pointers would be appreciated.

thank

+5
source share
2 answers

I just try to use different formats until I get hit:

public static String toUtcDate(String dateStr) {
    SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    // Add other parsing formats to try as you like:
    String[] dateFormats = {"yyyy-MM-dd", "MMM dd, yyyy hh:mm:ss Z"}; 
    for (String dateFormat : dateFormats) {
        try {
            return out.format(new SimpleDateFormat(dateFormat).parse(dateStr));
        } catch (ParseException ignore) { }
    }
    throw new IllegalArgumentException("Invalid date: " + dateStr);
}

, .

+11

: , ISO 8601, java.util.Date

, , UTC.


: joda, jaxb.

, ?

String dateStr = "2012-05-23T00:00:00-0400";
String dateStr1 = "May 24, 2012 04:57:40 GMT";
String dateStr2 = "2011-06-21";

, , DateFormat.getDateTimeInstance(...,...), , , , .

0

All Articles