余游 2012-08-30 10:37
浏览 481
已采纳

java文件中校验日期和时间格式,急求解答

现在需要在java文件中校验日期是否符合yyyy-mm-dd格式并且为有效日期,也就是说不能出现0000-00-00这种的错误形式,请问有没有什么好办法?另外,还要校验时间格式,时间格式为 xx:xx:xx,时间不允许出现24:00:00这种情况。请问有没有对这方面比较牛的,麻烦给解答一下了 :idea:

  • 写回答

6条回答 默认 最新

  • _1_1_7_ 2012-08-30 16:22
    关注

    [code="java"]

    static int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    
    /**
     * @param date yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isValidDate(String date) {
        try {
            int year = Integer.parseInt(date.substring(0, 4));
            if (year <= 0)
                return false;
            int month = Integer.parseInt(date.substring(5, 7));
            if (month <= 0 || month > 12)
                return false;
            int day = Integer.parseInt(date.substring(8, 10));
            if (day <= 0 || day > DAYS[month])
                return false;
            if (month == 2 && day == 29 && !isGregorianLeapYear(year)) {
                return false;
            }
            int hour = Integer.parseInt(date.substring(11, 13));
            if (hour < 0 || hour > 23)
                return false;
            int minute = Integer.parseInt(date.substring(14, 16));
            if (minute < 0 || minute > 59)
                return false;
            int second = Integer.parseInt(date.substring(17, 19));
            if (second < 0 || second > 59)
                return false;
    
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static final boolean isGregorianLeapYear(int year) {
        return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    }
    public static void main(String[] args) {
        System.out.println(isValidDate("2100-02-29 23:00:01"));
    }
    

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导