本文主要是介绍java 日期校验yyyymmdd,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 == 0 && vYear % 100 != 0 || vYear % 400 == 0) {isLeapYear = true;}// 判断月份// 1.判断月份if (month.startsWith("0")) {String units4Month = month.substring(1, 2);int vUnits4Month = Integer.parseInt(units4Month);if (vUnits4Month == 0) {return false;}if (vUnits4Month == 2) {// 获取2月的天数int vDays4February = Integer.parseInt(day);if (isLeapYear) {if (vDays4February > 29)return false;} else {if (vDays4February > 28)return false;}}} else {// 2.判断非0打头的月份是否合法int vMonth = Integer.parseInt(month);if (vMonth != 10 && vMonth != 11 && vMonth != 12) {return false;}}// 判断日期// 1.判断日期if (day.startsWith("0")) {String units4Day = day.substring(1, 2);int vUnits4Day = Integer.parseInt(units4Day);if (vUnits4Day == 0) {return false;}} else {// 2.判断非0打头的日期是否合法int vDay = 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 blocke.printStackTrace();return false;}}public static void main(String[] args) {boolean result1 = DateUtil.isValidDate("20150203"); //trueboolean result2 = DateUtil.isValidDate("20150229"); //falseboolean result3 = DateUtil.isValidDate("20000229"); //trueboolean result4 = DateUtil.isValidDate("2015918"); //falseSystem.out.println(result1);System.out.println(result2);System.out.println(result3);System.out.println(result4);}
}
最近做了一个跑批,因为是以日期作为批次号,所以为防止客户输入错误,还得需要做一个格式校验,所以以上mark一下。
这篇关于java 日期校验yyyymmdd的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!