Java如何檢查日期格式是否正確?

2019-10-16 22:25:37

在Java程式設計中,如何檢查日期格式是否正確?

以下範例演示如何使用String類的matches()方法檢查日期格式是否正確。

package com.yiibai;

public class CheckDateFormat {
    public static void main(String[] argv) {
        boolean isDate = false;
        String date1 = "9-15-1998";
        String date2 = "1997-08-16";
        String datePattern = "\\d{4}-\\d{1,2}-\\d{1,2}";

        isDate = date1.matches(datePattern);
        System.out.println("Date :" + date1 + ": matches with the this date Pattern:" + datePattern + "Ans:" + isDate);

        isDate = date2.matches(datePattern);
        System.out.println("Date :" + date2 + ": matches with the this date Pattern:" + datePattern + "Ans:" + isDate);
    }
}

上述程式碼範例將產生以下結果 -

Date :8-05-1998: matches with the this date Pattern:\d{4}-\d{1,2}-\d{1,2}Ans:false
Date :1997-08-16: matches with the this date Pattern:\d{4}-\d{1,2}-\d{1,2}Ans:true

範例-2

以下是檢查日期是否正確格式的另一個範例。

package com.yiibai;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckDateFormat2 {
    public static void main(String args[]) {
        List dates = new ArrayList();
        dates.add("1990-12-21");
        dates.add("1990-12-31");
        dates.add("1990-12-32");
        dates.add("09-12-12");
        dates.add("2001-02-10");
        String regex = "^([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|[12][0-9]|0[1-9])$";
        Pattern pattern = Pattern.compile(regex);

        for (Object date : dates) {
            Matcher matcher = pattern.matcher((CharSequence) date);
            System.out.println(date + " : " + matcher.matches());
        }
    }
}

上述程式碼範例將產生以下結果 -

1990-12-21 : true
1990-12-31 : true
1990-12-32 : false
09-12-12 : false
2001-02-10 : true