How to create a universal date formatter in Java for Solr?
•
Java
I have a request that you can pass the date in the following format before indexing the date to Solr The following is an example of a delivery date
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 I can't write a general program that supports various formats It will eventually throw a parsing exception
I have also tried joda time, but so far I have not successfully converted UTC
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 goal?
Any pointers would be appreciated
thank you
Solution
I just tried various formats until I was popular:
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 didn't know there was a library that could do that
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
