java严格验证日期是否正确的代码

 1 package com.xxxx.util;
 2 
 3 /**
 4  * 输入日期 并进行验证格式是否正确
 5  */
 6 public class FDate {
 7 
 8     public static void main(String[] args) {
 9         System.out.println(validate("2018-06-30t"));
10     }
11     
12     /**
13      * 检查是否是闰年
14      * 
15      * @param year
16      * @return
17      */
18     public static boolean run(int year) {
19         if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {// 是闰年
20 //            System.out.print(year + "是闰年!  ");
21             return true;
22         } else {
23             return false;
24         }
25     }
26 
27     public static boolean validate(String dateStr) {
28         String msg ="";
29         String[] data = new String[3];
30         boolean flag = true; // 若不符合规则将值改为false
31         String year = "[0-9]{4}";//
32         String month = "[0-9]||0[0-9]||1[12]";//
33         String day = "[0-9]||[0-2][0-9]||3[01]";//
34         int YEAR = 0;
35         String str = dateStr;// 输入的字符串
36         data = str.split("[-/.+]");
37         // 最基本的检查格式 begin
38         if (!data[0].matches(year)) {
39             msg = "年不对";
40             flag = false;
41         }
42         if (!data[1].matches(month)) {
43             msg = "月不对";
44             flag = false;
45         }
46         if (!data[2].matches(day)) {
47             msg = "日不对";
48             flag = false;
49         }
50         // end
51         YEAR = Integer.valueOf(data[0]);
52         boolean run = run(YEAR);// run 为true是闰年否则是 非闰年
53         if (run) {// 闰年
54             if (data[1].matches("0[2]||2")) {// 这里是闰年的2月
55                 if (!data[2].matches("0[1-9]||[1-9]||1[0-9]||2[0-9]")) {
56                     flag = false;
57                     msg = "2月份的天数不对";
58                 }
59             }
60         } else {// 非闰年
61             if (data[1].matches("0[2]||2")) {// 这里是平年的2月
62                 if (!data[2].matches("0[1-9]||[1-9]||1[0-9]||2[0-8]")) {
63                     flag = false;
64                     msg = "2月份的天数不对";
65                 }
66             }
67         }
68 
69         // 下面判断除了2月份的大小月天数
70         if (data[1].matches("0[13578]||[13578]||1[02]")) {// 这里是大月
71             if (!data[2].matches("0[1-9]||[1-9]||[12][0-9]||3[01]")) {
72                 flag = false;
73                 msg = data[2] + " 天数不对";
74             }
75         } else if (data[1].matches("0[469]||[469]||11")) {// 这里是小月
76             if (!data[2].matches("0[1-9]||[1-9]||[12][0-9]||30")) {
77                 flag = false;
78                 msg = data[2] + " 天数不对";
79             }
80         }
81 
82         if (flag) {
83             msg = "日期格式正确";
84         }
85         
86         return flag;
87     }
88 
89 }

猜你喜欢

转载自www.cnblogs.com/shamo89/p/9219902.html
今日推荐