Validate Date

校验一个文本文件中某个字符串(A)是否是合法日期的方法:
         
               1.A应该不能为空,
               2.A应该是一个纯数字的字符串,且其长度和日期格式的长度相匹配,
               3.利用字符串的转换函数,将A按照日期格式转换成日期B
               4.利用日期转换函数,将B按照日期格式转换成字符串C,
               5.比较A和C是否相等,如果不相等,则A不是一个合法的日期,否则A是

1.StringUtils.isEmpty(Object);

2.
private static final String NUMBER_FORMAT_REGEX = "(^\\d*[.]?\\d$)";
private static final Pattern NUMBER_FORMAT_PATTERN =       Pattern.compile(NUMBER_FORMAT_REGEX);

/**
* Validate digit format.
*
* @param number
*            the number
* @return the boolean
*/
public Boolean validateDigitFormat(String number) {
return NUMBER_FORMAT_PATTERN.matcher(number).matches();
}


DateUtils:
/**
* Parses the str to date.
*
* @param dateStr
*            the date str
* @param pattern
*            the pattern
* @return the date
* @throws ParseException
*             the parse exception
*/
3.public static Date parseStrToDate(String dateStr, String pattern) throws ParseException {
Date result = null;
if (StringUtils.isNotEmpty(dateStr)) {
return new SimpleDateFormat(pattern).parse(dateStr);
}
return result;
}

/**
* Parses the date to str.
*
* @param date
*            the date
* @param pattern
*            the pattern
* @return the string
*/
4.public static String parseDateToStr(Date date, String pattern) {
String result = null;
if (date != null) {
return new SimpleDateFormat(pattern).format(date);
}
return result;
}

/**
* Validate date by date format.
*
* @param dateStr
*            the date str
* @param pattern
*            the pattern
* @return the boolean
* @throws ParseException
*             the parse exception
*/
5.public Boolean validateDateByDateFormat(String dateStr, String pattern) throws ParseException {
Date strToDate = DateUtils.parseStrToDate(dateStr, pattern);
String dateToStr = DateUtils.parseDateToStr(strToDate, pattern);
return strToDate.equals(dateToStr);
}

猜你喜欢

转载自lihongtai.iteye.com/blog/2153544