简体   繁体   中英

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.

One option would be to concatenate the current year onto the incoming date string, and then parse:

String ts = "Oct 10 11:05:03";
int currYear = Calendar.getInstance().get(Calendar.YEAR);
ts = String.valueOf(currYear) + " " + ts;

Date date = getDate(ts, "yyyy MMM d HH:mm:ss");
System.out.println(date);

Wed Oct 10 11:05:03 CEST 2018

Demo

Note that we could have used StringBuilder above, but the purpose of brevity of code, I used raw string concatenations instead. I also fixed a few typos in your helper method getDate() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM