java - Generic date parsing in java
问题描述
I have date strings in various formats like Oct 10 11:05:03 or 12/12/2016 4:30 etc If I do
// some code...
getDate("Oct 10 11:05:03", "MMM d HH:mm:ss");
// some code ...
The date gets parsed, but I am getting the year as 1970 (since the year is not specified in the string.) But I want the year as current year if year is not specidied. Same applies for all fields.
here is my getDate function:
public Date getDate(dateStr, pattern) {
SimpleDateFormat parser = new SimpleDateFormat(pattern);
Date date = parser.parse(myDate);
return date;
}
can anybody tell me how to do that inside getDate function (because I want a generic solution)?
Thanks in advance!
解决方案
If you do not know the format in advance, you should list the actual formats you are expecting and then try to parse them. If one fails, try the next one.
Here is an example of how to fill in the default.
You'll end up with something like this:
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("ddMM")
.parseDefaulting(YEAR, currentYear)
.toFormatter();
LocalDate date = LocalDate.parse("yourstring", f);
Or even better, the abovementioned formatter class supports optional elements. Wrap the year specifier in square brackets and the element will be optional. You can then supply a default with parseDefaulting
.
Here is an example:
String s1 = "Oct 5 11:05:03";
String s2 = "Oct 5 1996 13:51:56"; // Year supplied
String format = "MMM d [uuuu ]HH:mm:ss";
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern(format)
.parseDefaulting(ChronoField.YEAR, Year.now().getValue())
.toFormatter(Locale.US);
System.out.println(LocalDate.parse(s1, f));
System.out.println(LocalDate.parse(s2, f));
Note: Dates and times are not easy. You should take into consideration that date interpreting is often locale-dependant and this sometimes leads to ambiguity. For example, the date string "05/12/2018" means the 12th of May, 2018 when you are American, but in some European areas it means the 5th of December 2018. You need to be aware of that.
推荐阅读
- bash - 我正在使用 Pandoc 将 Markdown 转换为 .docx - 如何从生成的文件名中删除 .md?
- php - PHP通过引用传递类中相同对象的函数
- jestjs - Jest 过时快照警告导致测试失败:退出 Jest 时忽略警告
- angular - 在执行流的其余部分之前,如何强制流等待 interval() 运算符完成?
- jquery - 当我在手机浏览器中查看我的页面时,JavaScript 不起作用
- r - 如何处理具有许多 0 的时间序列数据?
- javascript - 当我单击选择时,useEffect() 使我的应用程序挂起
- azure - ARM模板:从不同的文件中获取参数
- scala - Scala 字符串到日期的转换
- file-upload - Hapi Js文件上传苦苦挣扎