如何在 Java 中为 Solr 创建通用日期格式化程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10762428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a generic date formatter in java for Solr?
提问by Shamik
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
我有一个要求,在将日期索引到 Solr 之前,可以按以下格式传递它们。以下是传递日期的示例
String dateStr = "2012-05-23T00:00:00-0400";
String dateStr1 = "May 24, 2012 04:57:40 GMT";
String dateStr2 = "2011-06-21";
标准的 Solr 格式是 "yyyy-MM-dd'T'HH:mm:ss'Z'""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.
我尝试过 SimpleDateFormat 但无法编写通用程序来支持各种格式。它最终抛出解析异常。
I also tried joda time, but not been succeful so far in UTC conversion.
我也尝试过 joda time,但到目前为止在 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 ?
是否有标准库来实现这一目标?
Any pointers will be appreciated.
任何指针将不胜感激。
Thanks
谢谢
回答by Bohemian
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.
我不知道这样做的图书馆。
回答by Sebastien Lorber
Here is the answer: Converting ISO 8601-compliant String to java.util.Date
答案如下: 将符合 ISO 8601 的字符串转换为 java.util.Date
Once you have your Date, you know how to get your UTC time.
一旦你有了你的日期,你就知道如何获得你的 UTC 时间。
Edit: The accepted answer doesn't use joda time but jaxb.
编辑:接受的答案不使用 joda 时间,而是使用 jaxb。
By the way, where do these formats come from?
顺便问一下,这些格式是从哪里来的?
String dateStr = "2012-05-23T00:00:00-0400";
String dateStr1 = "May 24, 2012 04:57:40 GMT";
String dateStr2 = "2011-06-21";
If they are different from a locale to another, it may be possible they were generated by DateFormat.getDateTimeInstance(...,...) so perhaps try to figure out which has been used.
如果它们从一个区域设置到另一个区域设置不同,它们可能是由 DateFormat.getDateTimeInstance(...,...) 生成的,因此也许尝试找出已使用的那个。