在 Java 中解析任何日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3389348/
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
Parse any date in Java
提问by Max
I know this question is asked quite a bit, and obviously you can't parse any arbitrary date. However, I find that the python-dateutil library is able to parse every date I throw at it, all while requiring absolutely zero effort in figuring out a date format string. Joda time is always sold as being a great Java date parser, but it still requires you to decide what format your date is in before you pick a Format (or create your own). You can't just call DateFormatter.parse(mydate) and magically get a Date object back.
我知道这个问题问了很多,显然你不能解析任何任意日期。但是,我发现 python-dateutil 库能够解析我抛出的每个日期,同时在找出日期格式字符串方面完全不需要付出任何努力。Joda 时间总是被认为是一个很棒的 Java 日期解析器,但它仍然需要您在选择格式(或创建自己的格式)之前决定日期的格式。您不能只调用 DateFormatter.parse(mydate) 并神奇地取回 Date 对象。
For example, the date "Wed Mar 04 05:09:06 GMT-06:00 2009" is properly parsed with python-dateutil:
例如,日期“Wed Mar 04 05:09:06 GMT-06:00 2009”可以用 python-dateutil 正确解析:
import dateutil.parser
print dateutil.parser.parse('Wed Mar 04 05:09:06 GMT-06:00 2009')
but the following Joda time call doesn't work:
但以下 Joda 时间调用不起作用:
String date = "Wed Mar 04 05:09:06 GMT-06:00 2009";
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dt = fmt.parseDateTime(date);
System.out.println(date);
And creating your own DateTimeFormatter defeats the purpose, since that seems to be the same as using SimpleDateFormatter with the correct format string.
创建您自己的 DateTimeFormatter 违背了目的,因为这似乎与使用 SimpleDateFormatter 和正确的格式字符串相同。
Is there a comparable way to parse a date in Java, like python-dateutil? I don't care about errors, I just want it to mostly perfect.
有没有类似的方法来解析 Java 中的日期,比如 python-dateutil?我不在乎错误,我只希望它最完美。
回答by Robert Diana
What I have seen done is a Date util class that contains several typical date formats. So, when DateUtil.parse(date) is called, it tries to parse the date with each date format internally and only throws exceptions if none of the internal formats can parse it.
我所看到的是一个 Date util 类,它包含几种典型的日期格式。因此,当 DateUtil.parse(date) 被调用时,它会尝试在内部解析每个日期格式的日期,并且只有在没有任何内部格式可以解析它时才会抛出异常。
It is basically a brute force approach to your problem.
它基本上是解决您的问题的蛮力方法。
回答by BalusC
Your best bet is really asking help to regex to match the date format pattern and/or to do brute forcing.
您最好的选择是寻求帮助以正则表达式匹配日期格式模式和/或进行暴力破解。
Several years ago I wrote a little silly DateUtil
classwhich did the job. Here's an extract of relevance:
几年前,我写了一个愚蠢的DateUtil
类来完成这项工作。这是相关性的摘录:
private static final Map<String, String> DATE_FORMAT_REGEXPS = new HashMap<String, String>() {{
put("^\d{8}$", "yyyyMMdd");
put("^\d{1,2}-\d{1,2}-\d{4}$", "dd-MM-yyyy");
put("^\d{4}-\d{1,2}-\d{1,2}$", "yyyy-MM-dd");
put("^\d{1,2}/\d{1,2}/\d{4}$", "MM/dd/yyyy");
put("^\d{4}/\d{1,2}/\d{1,2}$", "yyyy/MM/dd");
put("^\d{1,2}\s[a-z]{3}\s\d{4}$", "dd MMM yyyy");
put("^\d{1,2}\s[a-z]{4,}\s\d{4}$", "dd MMMM yyyy");
put("^\d{12}$", "yyyyMMddHHmm");
put("^\d{8}\s\d{4}$", "yyyyMMdd HHmm");
put("^\d{1,2}-\d{1,2}-\d{4}\s\d{1,2}:\d{2}$", "dd-MM-yyyy HH:mm");
put("^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{2}$", "yyyy-MM-dd HH:mm");
put("^\d{1,2}/\d{1,2}/\d{4}\s\d{1,2}:\d{2}$", "MM/dd/yyyy HH:mm");
put("^\d{4}/\d{1,2}/\d{1,2}\s\d{1,2}:\d{2}$", "yyyy/MM/dd HH:mm");
put("^\d{1,2}\s[a-z]{3}\s\d{4}\s\d{1,2}:\d{2}$", "dd MMM yyyy HH:mm");
put("^\d{1,2}\s[a-z]{4,}\s\d{4}\s\d{1,2}:\d{2}$", "dd MMMM yyyy HH:mm");
put("^\d{14}$", "yyyyMMddHHmmss");
put("^\d{8}\s\d{6}$", "yyyyMMdd HHmmss");
put("^\d{1,2}-\d{1,2}-\d{4}\s\d{1,2}:\d{2}:\d{2}$", "dd-MM-yyyy HH:mm:ss");
put("^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{2}:\d{2}$", "yyyy-MM-dd HH:mm:ss");
put("^\d{1,2}/\d{1,2}/\d{4}\s\d{1,2}:\d{2}:\d{2}$", "MM/dd/yyyy HH:mm:ss");
put("^\d{4}/\d{1,2}/\d{1,2}\s\d{1,2}:\d{2}:\d{2}$", "yyyy/MM/dd HH:mm:ss");
put("^\d{1,2}\s[a-z]{3}\s\d{4}\s\d{1,2}:\d{2}:\d{2}$", "dd MMM yyyy HH:mm:ss");
put("^\d{1,2}\s[a-z]{4,}\s\d{4}\s\d{1,2}:\d{2}:\d{2}$", "dd MMMM yyyy HH:mm:ss");
}};
/**
* Determine SimpleDateFormat pattern matching with the given date string. Returns null if
* format is unknown. You can simply extend DateUtil with more formats if needed.
* @param dateString The date string to determine the SimpleDateFormat pattern for.
* @return The matching SimpleDateFormat pattern, or null if format is unknown.
* @see SimpleDateFormat
*/
public static String determineDateFormat(String dateString) {
for (String regexp : DATE_FORMAT_REGEXPS.keySet()) {
if (dateString.toLowerCase().matches(regexp)) {
return DATE_FORMAT_REGEXPS.get(regexp);
}
}
return null; // Unknown format.
}
(cough, double brace initialization, cough, it was just to get it all to fit in 100 char max length ;) )
(咳嗽,双括号初始化,咳嗽,这只是为了让它适合 100 个字符的最大长度;))
You can easily expand it yourself with new regex and dateformat patterns.
您可以使用新的正则表达式和日期格式模式轻松地自己扩展它。
回答by Cacovsky
There is a nice library called Nattywhich I think fits your purposes:
有一个名为Natty的不错的库,我认为它符合您的目的:
Natty is a natural language date parser written in Java. Given a date expression, natty will apply standard language recognition and translation techniques to produce a list of corresponding dates with optional parse and syntax information.
Natty 是用 Java 编写的自然语言日期解析器。给定一个日期表达式,natty 将应用标准语言识别和翻译技术来生成具有可选解析和语法信息的对应日期列表。
You can also try it online!
您也可以在线试用!
回答by sulin
You could try dateparser.
你可以试试dateparser。
It can recognize any Stringautomatically, and parse it into Date, Calendar, LocalDateTime, OffsetDateTimecorrectly and quickly(1us~1.5us
).
它可以自动识别任何字符串,并正确快速地将其解析为Date、Calendar、LocalDateTime、OffsetDateTime1us~1.5us
。
It doesn't based on any natural language analyzer
or SimpleDateFormat
or regex.Pattern
.
它不基于任何natural language analyzer
或SimpleDateFormat
或regex.Pattern
。
With it, you don't have to prepare any appropriate patterns like yyyy-MM-dd'T'HH:mm:ss.SSSZ
or yyyy-MM-dd'T'HH:mm:ss.SSSZZ
:
有了它,您不必准备任何适当的模式,例如yyyy-MM-dd'T'HH:mm:ss.SSSZ
或yyyy-MM-dd'T'HH:mm:ss.SSSZZ
:
Date date = DateParserUtils.parseDate("2015-04-29T10:15:00.500+0000");
Calendar calendar = DateParserUtils.parseCalendar("2015-04-29T10:15:00.500Z");
LocalDateTime dateTime = DateParserUtils.parseDateTime("2015-04-29 10:15:00.500 +00:00");
All works fine, please enjoy it.
一切正常,请尽情享受。
回答by Shashidhar Reddy
I have no idea about this parsing how to do in python. In java we can do like this
我不知道这个解析如何在 python 中执行。在java中我们可以这样做
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date normalDate = null;
java.sql.Date sqlDate = null;
normalDate = sdf1.parse(date);
sqlDate = new java.sql.Date(normalDate.getTime());
System.out.println(sqlDate);
i think like java some predefined functions will be there in python. You can follow this method. This methods parse the String date to Sql Date (dd-MM-yyyy);
我认为像 java 一样,python 中也会有一些预定义的函数。你可以按照这个方法。此方法将字符串日期解析为 Sql 日期 (dd-MM-yyyy);
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class HelloWorld{
public static void main(String []args){
String date ="26-12-2019";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date normalDate = null;
java.sql.Date sqlDate = null;
if( !date.isEmpty()) {
try {
normalDate = sdf1.parse(date);
sqlDate = new java.sql.Date(normalDate.getTime());
System.out.println(sqlDate);
} catch (ParseException e) {
}
}
}
}
execute this!
执行这个!
回答by Mahdi
//download library: org.ocpsoft.prettytime.nlp.PrettyTimeParser
String str = "2020.03.03";
Date date = new PrettyTimeParser().parseSyntax(str).get(0).getDates().get(0);
System.out.println(date)