I have a date stored in a string and I need to validate whether it represents a date or weekdate in ISODateFormat.
String is acceptable if it is in either format.
I can build 2 formatters and pass the string and check where they both throw exceptions and verify it.
String date;
final DateTimeFormatter dateFormatter = ISODateTimeFormat.date();
final DateTimeFormatter weekdateFormatter = ISODateTimeFormat.weekDate();
boolean isDate=true,isWeekDate=true;
try {
dateFormatter.parseDateTime(date);
}
catch (IllegalArgumentException e) {
isDate =false;
}
try {
weekdateFormatter.parseDateTime(date);
}
catch (IllegalArgumentException e) {
isWeekDate =false;
}
if(!isDate && !isWeekDate)
throw UserDefinedException();
Is there any better way to do it?
additional method
/**
* @return null if string is invalid
*/
public static DateTime checkDate(String dateAsString, DateTimeFormatter formatter)
{
DateTime retVal = null;
try {
retVal = formatter.parseDateTime(dateAsString);
} catch (IllegalArgumentException ex){
}
return retVal;
}
usage
String date = "someString";
if (checkDate(date, ISODateTimeFormat.date()) == null
|| checkDate(date, ISODateTimeFormat.weekDate()) == null)
{
throw new UserDefinedException();
}
or utils method for multiple formats
/**
* @return null if string is invalid
*/
public static DateTime checkDate(String dateAsString,
DateTimeFormatter[] formatters)
{
DateTime retVal = null;
for (final DateTimeFormatter formatter : formatters)
{
try
{
retVal = formatter.parseDateTime(dateAsString);
}
catch (IllegalArgumentException ex)
{
}
if (retVal != null)
{
break;
}
}
return retVal;
}
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.