Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic date formatter in java for Solr?

I've a requirement where date can be passed in the following formats before indexing them to Solr. Here are the examples of dates being passed

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've tried SimpleDateFormat but is not able to write a generic program to support various formats. It ends up throwing parse exceptions.

I also tried joda time, but not been succeful 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 to achieve this ?

Any pointers will be appreciated.

Thanks

like image 247
Shamik Avatar asked May 25 '12 23:05

Shamik


People also ask

How do you format a date in Java?

Java SimpleDateFormat with Locale String pattern = "EEEEE MMMMM yyyy HH:mm:ss. SSSZ"; SimpleDateFormat simpleDateFormat =new SimpleDateFormat(pattern, new Locale("fr", "FR")); String date = simpleDateFormat. format(new Date()); System.

How do you create a custom date in Java?

You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.


1 Answers

I just try the various formats until I get a 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);
}

I'm not aware of a library that does this.

like image 63
Bohemian Avatar answered Nov 09 '22 17:11

Bohemian