如何使用Swing验证在JTextField中输入的日期和时间? [重复]

时间:2022-12-09 19:29:27

This question already has an answer here:

这个问题在这里已有答案:

I want to validate data entered by user in 'date and time' JTextField with (yyyy-MM-dd hh:mm:ss.SSS ) this format , please help me to get out of this, am not getting any idea.

我想验证用户在'日期和时间'JTextField中输入的数据(yyyy-MM-dd hh:mm:ss.SSS)这种格式,请帮我摆脱这个,我不知道。

How to validate entered data with this format (yyyy-MM-dd hh:mm:ss.SSS)?

如何使用这种格式验证输入的数据(yyyy-MM-dd hh:mm:ss.SSS)?

1 个解决方案

#1


1  

You can validate like this, if exception you need to notify user that it is not a valid format

您可以像这样进行验证,如果异常需要通知用户它不是有效格式

    try {
        Date date = null;
        String inputDate = "2016-01-07 10:11:30.500";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        dateFormat.setLenient(false);
        date = dateFormat.parse(inputDate);
        System.out.println(date);
    } catch (ParseException parseException) { 
        //Code should be added to handle invalid date format
    }

#1


1  

You can validate like this, if exception you need to notify user that it is not a valid format

您可以像这样进行验证,如果异常需要通知用户它不是有效格式

    try {
        Date date = null;
        String inputDate = "2016-01-07 10:11:30.500";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
        dateFormat.setLenient(false);
        date = dateFormat.parse(inputDate);
        System.out.println(date);
    } catch (ParseException parseException) { 
        //Code should be added to handle invalid date format
    }