今天做Android的时候遇到一个需求,即校验yyyyMMdd格式的日期,没有搜索到合适的于是自己写了一个简单的小算法,权当复习SE了,顺便记录一下~
package com.wl.cigrec.util;
public class DateUtil {
/**
* 判断参数的格式是否为“yyyyMMdd”格式的合法日期字符串
*
* @author Liang.Wang
* @since 02/24/15
* @param str
* @return true/false
*/
public static boolean isValidDate(String str) {
try {
if (str != null && !str.equals("")) {
if (str.length() == 8) {
// 闰年标志
boolean isLeapYear = false;
String year = str.substring(0, 4);
String month = str.substring(4, 6);
String day = str.substring(6, 8);
int vYear = Integer.parseInt(year);
// 判断年份是否合法
if (vYear <1900 || vYear > 2200) {
return false;
}
// 判断是否为闰年
if (vYear % 4 &#61;&#61; 0 && vYear % 100 !&#61; 0 || vYear % 400 &#61;&#61; 0) {
isLeapYear &#61; true;
}
// 判断月份
// 1.判断月份
if (month.startsWith("0")) {
String units4Month &#61; month.substring(1, 2);
int vUnits4Month &#61; Integer.parseInt(units4Month);
if (vUnits4Month &#61;&#61; 0) {
return false;
}
if (vUnits4Month &#61;&#61; 2) {
// 获取2月的天数
int vDays4February &#61; Integer.parseInt(day);
if (isLeapYear) {
if (vDays4February > 29)
return false;
} else {
if (vDays4February > 28)
return false;
}
}
} else {
// 2.判断非0打头的月份是否合法
int vMonth &#61; Integer.parseInt(month);
if (vMonth !&#61; 10 && vMonth !&#61; 11 && vMonth !&#61; 12) {
return false;
}
}
// 判断日期
// 1.判断日期
if (day.startsWith("0")) {
String units4Day &#61; day.substring(1, 2);
int vUnits4Day &#61; Integer.parseInt(units4Day);
if (vUnits4Day &#61;&#61; 0) {
return false;
}
} else {
// 2.判断非0打头的日期是否合法
int vDay &#61; Integer.parseInt(day);
if (vDay <10 || vDay > 31) {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
boolean result1 &#61; DateUtil.isValidDate("20150203"); //true
boolean result2 &#61; DateUtil.isValidDate("20150229"); //false
boolean result3 &#61; DateUtil.isValidDate("20000229"); //true
boolean result4 &#61; DateUtil.isValidDate("2015918"); //false
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
System.out.println(result4);
}
}
OK&#xff0c;碎觉&#xff0c;明天年后第一天上班~在2015年一定要更加努力~务必彻彻底底的拿下Android~加油&#xff01;