首页 > 解决方案 > 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!

标签: javadatedate-format

解决方案


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.


推荐阅读