gpt4 book ai didi

android - Android 中的日期验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:51 26 4
gpt4 key购买 nike

我是 Android 编程新手,目前正在开发一款应用。有人可以帮助我验证用户输入的日期是否有效吗?

private Pattern pattern;
private Matcher matcher;

private static final String DATE_PATTERN =
"(0?[1-9]|1[012]) [/.-] (0?[1-9]|[12][0-9]|3[01]) [/.-] ((19|20)\\d\\d)";


/**
* Validate date format with regular expression
* @param date date address for validation
* @return true valid date format, false invalid date format
*/
public boolean validate(final String date){

matcher = pattern.matcher(date);

if(matcher.matches()){
matcher.reset();

if(matcher.find()){
String day = matcher.group(1);
String month = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));

if (day.equals("31") &&
(month.equals("4") || month .equals("6") || month.equals("9") ||
month.equals("11") || month.equals("04") || month .equals("06") ||
month.equals("09"))) {
return false; // only 1,3,5,7,8,10,12 has 31 days
}
}

else{
return false;
}
}
else{
return false;
}
}

最佳答案

private Pattern pattern;
private Matcher matcher;

private static final String DATE_PATTERN =
"(0?[1-9]|1[012]) [/.-] (0?[1-9]|[12][0-9]|3[01]) [/.-] ((19|20)\\d\\d)";


/**
* Validate date format with regular expression
* @param date date address for validation
* @return true valid date format, false invalid date format
*/
public boolean validate(final String date){

matcher = pattern.matcher(date);

if(matcher.matches()){
matcher.reset();

if(matcher.find()){
String day = matcher.group(1);
String month = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));

if (day.equals("31") &&
(month.equals("4") || month .equals("6") || month.equals("9") ||
month.equals("11") || month.equals("04") || month .equals("06") ||
month.equals("09"))) {
return false; // only 1,3,5,7,8,10,12 has 31 days
}

else if (month.equals("2") || month.equals("02")) {
//leap year
if(year % 4==0){
if(day.equals("30") || day.equals("31")){
return false;
}
else{
return true;
}
}
else{
if(day.equals("29")||day.equals("30")||day.equals("31")){
return false;
}
else{
return true;
}
}
}

else{
return true;
}
}

else{
return false;
}
}
else{
return false;
}
}

并将这些代码放在您的 onClick() 上:

matcher = Pattern.compile(DATE_PATTERN).matcher(Birthday);

//Birthday validator
else if (!matcher.matches()) {
Toast.makeText(getApplicationContext(), "Invalid Birthday!", Toast.LENGTH_SHORt).show();
}

关于android - Android 中的日期验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17416595/

26 4 0
文章推荐: android - 查看是否安装了应用程序
文章推荐: javascript - 如何检查事件是否被触发?
文章推荐: android - 只有一个动画发生在 overridePendingTransition
文章推荐: javascript - 使用 webdriver.js,如何获取