java时间字符串格式校验

时间:2025-03-10 08:22:05

public class DateDome{

    /**

    * 字符串格式符合xxxx.(-)xx(x).(-)xx(x)可以进行校验

    * 正确则返回ture,错误则返回false

* */

    public static boolean validateTimeFormat(String memotime){

        /*

        * 字符串regex为自定义正则表达式,[123]表示1,2,3三个数字选择一个,

        * (\\d)表示0至9中任意一个数字,{3}表示前面临近的表达式重复3遍 

      * 年的取值范围1000至3999,也可以人为再添加     

  * 中间的用-或者.来拼接  不能同时使用-和.

     * [1-9]|([0][1-9])|([1][0-2] 来表示1至12月  

     * ([1-9])|([0][1-9])|([12]\d|([3][01]) 来表示1到31天* */

        String regex="([123]\\d{3}(-|\\.)(([1-9])|([0][1-9])|([1][0-2]))(-|\\.)(([1-9])|([0][1-9])|([12]\\d|([3][01]))))";

        Pattern  pattern= (regex);

        Matcher matcher = (memotime);

        if(!()){

            return false;

        }else {

            String[] times=null;

            if(("-")){

              times=memotime.split("-");

            }else {

              times=("\\.");

            }

            if ( <3) {

                return false;

            }

            Integer year = (times[0]);

            Integer month = (times[1]);

            Integer day = (times[2]);

            GregorianCalendar calendar=new GregorianCalendar();

            //闰年2月天数不能大于29

            if((year)&&(month==2)&&(day>29)){

                return false;

                //非闰年2月天数不能大于28

            }else if((!(year))&&(month ==2)&&(day>28)){

                return false;

            }else {

                switch (month){

                    case 4:

case 6:

case 9:

case 11:

if(day>30){

                            return false;

                        }else {

                            return  true;

                        }

                    default :

return  true;

                }

}

}

}

    public static void main(String[] args) {

        String date="2016.12.2";

        (validateTimeFormat(date));

    }

}