Reputation: 3984
I want to create a simple function that gets 2 params - date format(dd/mm/yyyy, dd-mm-yyyy etc...) and a string that in this format(1/4/2015, 1-4-2015).
First of all is there a way to check if the format is acceptable by SimpleDateFormat
and the next step if the dateInString
is today, here is my code:
public boolean checkDate(String dateInString, String format){
boolean result = false;
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
//parse the string to date
Date inputDate = dateFormat.parse(dateInString);
//check if the date is today using the format
//if the date is today then
result = true;
return result;
}
Upvotes: 0
Views: 671
Reputation: 1759
You could use this Utility class (DateUtils) with this implementation:
public boolean checkDate(String dateInString, String format){
try {
return DateUtils.isToday(new SimpleDateFormat(format).parse(dateInString));
} catch (ParseException e) {
return false;
}
}
Upvotes: 2
Reputation: 71
For checking the format you could do something like this:
SimpleDateFormat dateFormat;
try {
dateFormat = new SimpleDateFormat(format);
}
catch(IllegalArgumentException e){
//handle wrong format
}
Check if date is today
dateInString.equals(dateFormat.format(new Date()))
Have a look at Joda Time Library which is much more convenient ;)
PS: Have not tested the, but thats roughly the way to go.
A cleaner way would be to split the method up e.g.
Upvotes: 0