「java正则判断日期」java正则判断日期格式
今天给各位分享java正则判断日期的知识,其中也会对java正则判断日期格式进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
java如何判断输入日期格式是否为指定格式
可以使用正则表达式进行匹配替换,例如下面代码:
public class app50 {
public static void main(string[] args) {
string demo = "这个日期是2018/5/6书写出来的";
// xxxx年xx月xx日 格式
string demo2 = demo.replaceall("(\\d{4})/(\\d{1,2})/(\\d{1,2})", "$1年$2月$3日");
system.out.println(demo2);
// xxxx-xx-xx 格式
demo2 = demo.replaceall("(\\d{4})/(\\d{1,2})/(\\d{1,2})", "$1-$2-$3");
system.out.println(demo2);
}
}运行结果:
这个日期是2018年5月6日书写出来的
这个日期是2018-5-6书写出来的
Java里面效验日期的正则表达式
public static void main(String[] args)
{
String checkValue = "20000431112230";
String year = checkValue.substring(0, 4); // 获取年份
String month = checkValue.substring(4, 6); // 获取月份
Boolean isLeap = leapYear(Integer.parseInt(year)); // 判断闰年
System.out.println(isLeap);
StringBuffer eL= new StringBuffer();
String longMonth = "01030507081012"; // 31天的月份
String fix = "([2][0-3]|[0-1][0-9]|[1-9])[0-5][0-9]([0-5][0-9]|[6][0])";
if(isLeap month.equals("02")){ // 针对2月份的情况 【闰年】
eL.append("\\d{4}([1][0-2]|[0][0-9])([2][0-1]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
}else if(!isLeap month.equals("02")){ // 针对2月份的情况 【非闰年】
eL.append("\\d{4}([1][0-2]|[0][0-9])([2][0-1]|[1-2][0-8]|[0][1-9]|[1-9])"+fix);
}else if(longMonth.contains(month)){ // 31天月份
eL.append("\\d{4}([1][0-2]|[0][0-9])([3][0-1]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
}else{ // 30天月份
eL.append("\\d{4}([1][0-2]|[0][0-9])([3][0]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
}
Pattern p = Pattern.compile(eL.toString());
Matcher m = p.matcher(checkValue);
boolean flag = m.matches();
if(flag )
{
System.out.println("格式正确");
}
else
{
System.out.println("格式错误");
}
}
public static boolean leapYear(int year) {
Boolean isLeap = false;
if (((year % 100 == 0) (year % 400 == 0))
|| ((year % 100 != 0) (year % 4 == 0)))
isLeap = true;
return isLeap;
}
java正则表达式中怎么判断是否包含日期格式字符串,例如
Regex reg = new Regex(@"(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)");
String str = "addfnews.sdfdcodfdcn/c/2010-08-12/004720877716.dddfddfdtml";
if (reg.IsMatch(str))
Console.WriteLine("True");
else
Console.WriteLine("False");
java用正则表达式判断字符串是不是时间
具体代码如下:
1 public static boolean isValidDate(String str) {
2 boolean convertSuccess=true;
3 // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
4 SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
5 try {
6 // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
7 format.setLenient(false);
8 format.parse(str);
9 } catch (ParseException e) {
10 // e.printStackTrace();
11 // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
12 convertSuccess=false;
13 }
14 return convertSuccess;
java正则判断日期的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java正则判断日期格式、java正则判断日期的信息别忘了在本站进行查找喔。
发布于:2022-12-21,除非注明,否则均为
原创文章,转载请注明出处。