java验证输入的格式是否正确

code小生 2015-08-17 09:41:06
需求是这样的:用户从键盘输入一个字符串(日期),程序中要判断输入的日期是否符合MM/dd这种格式?
请问大神这个该怎么做?关键是如何判断格式相同,不要求使用正则。
...全文
695 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
gukuitian 2015-08-18
  • 打赏
  • 举报
回复
    	
SimpleDateFormat d = new SimpleDateFormat("MM/dd");
String date = "01/30";
System.out.println(date.equals(d.format(d.parse(date))));
0萌萌哒0 2015-08-18
  • 打赏
  • 举报
回复
如果严格按照那个格式来看,字符串的长度是固定的,每个位置上的字符也是固定含义的,故方便编码。 现提供两种方法:

public static void main(String[] args) {
	// 正确输入
	final String input = new SimpleDateFormat("MM/dd").format(new Date());
	// 错误输入
	// String input = "6/12";
	System.out.println("Input is: " + input);
	// 正则版本
	Matcher mx = Pattern.compile("([01][0-9])/([0-3][0-9])").matcher(input);
	if(mx.matches()) {
		String m = mx.group(1), d = mx.group(2);
		int month = Integer.parseInt(m), day = Integer.parseInt(d);
		if(month > 0 && month <= 12 && day > 0 && day <= 31) {
			System.out.println("Match " + month + "/" + day);
		}
	}
	
	// 非正则版本
	try {
		int month = Integer.parseInt(input.substring(0, 2));
		char separator = input.charAt(2);
		int day = Integer.parseInt(input.substring(3));
		if(month >= 1 && month <= 12 && separator  == '/' && day >= 1 && day <= 31 ){
			System.out.println("Right Date format: " + month + separator + day);
		} else {
			System.out.println("Wrong Date format! " + input);
		}
	} catch (NumberFormatException e) {
		System.out.println("Wrong Date format! " + input);
	}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧