简体   繁体   English

Java-如何在日期输入中仅接受整数?

[英]Java - How to accept only integers on date input?

Hey guys so my project for checking a user's input of a date in the format of mm/dd/yyyy works, but now I need to modify it so that it rejects anything not numbers. 大家好,我的项目用于检查用户以mm / dd / yyyy格式输入的日期,但现在我需要对其进行修改,以便它拒绝任何非数字的内容。 For example if I input 12/5/abcd or aa/12/2014 it should return me an error. 例如,如果我输入12/5 / abcd或aa / 12/2014,则应返回错误。 At the moment if I enter a char or letters into the program it'll give an error saying something like "you should enter only valid integers". 目前,如果我在程序中输入一个字符或字母,则会出现错误消息,例如“您应该只输入有效的整数”。 I'm using a delimiter for "/" to separate months and days and \\r or enter/return at the end of the year to finish the user input. 我在使用分隔符“ /”来分隔月份和日期,并使用\\ r或在年底输入/返回以完成用户输入。

Only integer check won't work (consider someone enters 30-02-2013 仅整数检查将不起作用(请考虑有人输入30-02-2013

you need to validate Date specifically, You should use SimpleDateFormat with setLenient(false) 您需要专门验证Date,应该将SimpleDateFormatsetLenient(false)

Simply put an if condition to check the instance of integer on dd, mm and yy. 只需放置一个if条件即可检查dd,mm和yy上的整数实例。 Like 喜欢

if(x instanceof Integer){
         ...
}

我认为,使用Java正则表达式使用以下正则表达式来验证输入日期。

([0-9]{2})\\\\([0-9]{2})\\\\([0-9]{4})

If you only care about digits vs non-digits, you can validate with a simple regular expression. 如果您只关心数字与非数字,则可以使用简单的正则表达式进行验证。

import java.util.regex.*;


public class A{
    public static void main(String[] args) {
        String original =  "12/24/1014";
        Pattern mypattern = Pattern.compile("\\d{2}/\\d{2}/\\d{4}");
        System.out.println(mypattern.matcher(original).matches());
        // If not true, throw error.
    }
}

you can use below date. 您可以使用以下日期。

SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");

    boolean isValidDate(string input) {
         try {
              format.parse(input);
              return true;
         }
         catch(ParseException e){
              return false;
         }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM