开始时间和结束时间比较(java正则表达式实现)

package javaapplication1;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 *
 * @author yjmao
 * @version V1.0.0
 * @date 2012-10-11
 * @deprecated 开始时间和结束时间比较(正则表达式比较)
 */
public class checkDate {
    public static void main(String[] args){
        String startTime = "2012/10/25 12:25:56";
        String endTime = "2012-10-25 12:25:55";
        String error = checkDateFlag(startTime,endTime);
        System.err.println(error);
    }
    public static String checkDateFlag(String startTime,String endTime){
        StringBuilder year_mounth_date_hour_minute_second = new StringBuilder();
        //[1-9]{1}[0-9]{3}:匹配年1000-9999
        year_mounth_date_hour_minute_second.append("[1-9]{1}[0-9]{3}").append("-");
        //([1-9]|[0]{1}[1-9]{1}|[1]{1}[0-2]{1})匹配月:1-12或01-12或
        year_mounth_date_hour_minute_second.append("([1-9]|[0]{1}[1-9]{1}|[1]{1}[0-2]{1})").append("-");
        //([1-9]|[0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})匹配日:1-31或01-31
        year_mounth_date_hour_minute_second.append("([1-9]|[0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})").append("\\s*");
        //([0-9]|[0-1]{1}[0-9]{1}|[2]{1}[0-3]{1}):匹配小时:00-23或0-23
        year_mounth_date_hour_minute_second.append("([0-9]|[0-1]{1}[0-9]{1}|[2]{1}[0-3]{1}):");
        //([0-9]|[0-5]{1}[0-9]{1}):匹配分钟:00-59或0-59
        year_mounth_date_hour_minute_second.append("([0-9]|[0-5]{1}[0-9]{1}):");
        //([0-9]|[0-5]{1}[0-9]{1}):匹配秒:00-59或0-59
        year_mounth_date_hour_minute_second.append("([0-9]|[0-5]{1}[0-9]{1})");
        //匹配的字符串
        String regTime = year_mounth_date_hour_minute_second.toString();
        StringBuilder errorInfo = new StringBuilder();
        if(startTime.indexOf("/") != -1){
            startTime = startTime.replace("/", "-");
        }
        if(endTime.indexOf("/") != -1){
            endTime = endTime.replace("/", "-");
        }
        Pattern pattern = Pattern.compile(regTime);
        boolean startTimeFlag = pattern.matcher(startTime).matches();
        boolean endTimeFlag = pattern.matcher(endTime).matches();
        if(!startTimeFlag){
            errorInfo.append("开始时间格式不正确!");
        }
        if(!endTimeFlag){
            errorInfo.append("结束时间格式不正确!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null,endDate = null;
        try{
            startDate = sdf.parse(startTime);
            endDate = sdf.parse(endTime);
        }catch(Exception e){}
        if(startDate.after(endDate)){
            errorInfo.append("开始时间不能早于结束时间!");
        }
        return errorInfo.toString();
    }
}

你可能感兴趣的:(JAVA,SE)