如何验证时间戳(yyyy-MM-dd HH:mm:ss)和(yyyy-MM-dd)

时间:2014-08-12 05:16:52

标签: java

用户将输入日期,如yyyy-MM-ddyyyy-MM-dd hh:mm:ss。然后我需要验证时间戳。请帮助我。

我需要验证两种(yyyy-MM-dd)或(yyyy-MM-dd hh:mm:ss)的这些类型的验证。 如果用户输入日期是yyyy-MM-dd,那么将采用yyyy-MM-dd 00:00:00,如果用户输入日期是yyyy-MM-dd HH:mm:ss然后采取它作为它就像yyyy-MM-dd HH:mm:ss

 private static boolean dateValidate(String inputDate) {
                try {
                    String[] datePattern = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd "};
                    for (String pattern : datePattern) {
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        Date date = sdf.parse(inputDate);
                        String formattedDate = sdf.format(date);
                        if (inputDate.equals(formattedDate)) {
                            return true;
                        }
                    }
                } catch (ParseException ex) {
                    return false;
                }
                return false;

            }
            public static void main(String args[]) {
                // TODO Auto-generated method stub
                System.out.println(SampleTest.dateValidate("2014-02-22 22:23:22"));
                System.out.println(SampleTest.dateValidate("2014-02-22"));


            }

3 个答案:

答案 0 :(得分:1)

String[] formatStrings = { "yyyy-MM-dd hh:mm:ss", "yyyy-MM-dd" };

    for (String formatString : formatStrings) {
        try {
            Date date = new SimpleDateFormat(formatString).parse(<Your Input date here>);
            System.out.println(date.toString());
            break;
        } catch (ParseException e) {
            System.out.println("ex");
        }
    }

注意:String数组(formatStrings)的顺序很重要。有时候“yyyy-MM-dd”也可以解析其他日期格式。

答案 1 :(得分:0)

试试此代码

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the date");
    String inputDate = sc.nextLine();
    if(dateValidate(inputDate)){
        System.out.println("Input Date is in correct pattern");
    }
    else{
        System.out.println("Input date is in wrong pattern");
    }
}

private static boolean dateValidate(String inputDate) {
    try {
        String[] datePattern = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"};
        for (String pattern : datePattern) {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            Date date = sdf.parse(inputDate);
            String formattedDate = sdf.format(date);
            if (inputDate.equals(formattedDate)) {
                return true;
            }
        }
    } catch (ParseException ex) {
        return false;
    }
    return false;

}

答案 2 :(得分:0)

如果您只想验证它们,请尝试使用正则表达式

System.out.println(Pattern.matches
  ("^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$","2011-12-31"));

System.out.println(Pattern.matches
  ("((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) 
([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$","2014-02-22 23:33:32"));