java日期正则_java 日期正则匹配

import java.util.Calendar;

import java.util.Date;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import org.apache.commons.lang3.time.DateFormatUtils;

public class TimeUtil {

/**

* 验证时间字符串格式输入是否正确

* @param timeStr

* @return

*/

public static boolean valiDateTimeWithLongFormat(String timeStr) {

String format = "((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) "

+ "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";

Pattern pattern = Pattern.compile(format);

Matcher matcher = pattern.matcher(timeStr);

if (matcher.matches()) {

pattern = Pattern.compile("(\\d{4})-(\\d+)-(\\d+).*");

matcher = pattern.matcher(timeStr);

if (matcher.matches()) {

int y = Integer.valueOf(matcher.group(1));

int m = Integer.valueOf(matcher.group(2));

int d = Integer.valueOf(matcher.group(3));

if (d > 28) {

Calendar c = Calendar.getInstance();

c.set(y, m-1, 1);

int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);

return (lastDay >= d);

}

}

return true;

}

return false;

}

/**

* 验证时间字符串格式输入是否正确

* @param timeStr

* @return

*/

public static Date getDateTimeWithLongFormat(String timeStr) {

if(valiDateTimeWithLongFormat(timeStr)) {

String format = "((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) "

+ "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";

Pattern pattern = Pattern.compile(format);

Matcher matcher = pattern.matcher(timeStr);

if (matcher.matches()) {

pattern = Pattern.compile("(\\d{4})-(\\d+)-(\\d+) (\\d+):(\\d+):(\\d+)");

matcher = pattern.matcher(timeStr);

if (matcher.matches()) {

int y = Integer.valueOf(matcher.group(1));

int m = Integer.valueOf(matcher.group(2));

int d = Integer.valueOf(matcher.group(3));

int s = Integer.valueOf(matcher.group(4));

int f = Integer.valueOf(matcher.group(5));

int mm = Integer.valueOf(matcher.group(6));

Calendar c = Calendar.getInstance();

c.set(y, m-1, d,s,f,mm);

return c.getTime();

}

}

}

return null;

}

public static void main(String[] args){

/*System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-5-2 08:02:02"));

System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-02-29 08:02:02"));

System.out.println(TimeUtil.valiDateTimeWithLongFormat("2015-02-29 08:02:02"));

System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-02-02 082:02"));*/

Date dateTimeWithLongFormat = TimeUtil.getDateTimeWithLongFormat("2016-5-2 08:02:02");

String format = DateFormatUtils.format(dateTimeWithLongFormat, "yyyy-MM-dd HH:mm:ss");

System.out.println(format);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值