本人有个方法:
public class T {
public boolean t(Date d,String s) {时间格式:0 16 * * * (中间间隔一个空格)(从后往前分别代表:年 月 日 时 分)这个代表 每天的16点还有个测试:
public class TestT extends TestCase {
T t = new T(); public void testTFail() {
assertFalse(t.t(new Date(), "* 16"));
} public void testTSuccess2() {
assertTrue(t.t(new Date(), "0 16"));
} public void testTSuccess3() {
assertTrue(t.t(new Date(), "0 17 *"));
} public void testTSuccess4() {
assertTrue(t.t(new Date(), "16 10 * *"));
}这个只是部分情况,现在要求就是 我给定时间 跟当前时间比较 相等返回true 不等 返回flase 就是解析字符串跟当前时间比较,大侠们请指点
public class T {
public boolean t(Date d,String s) {时间格式:0 16 * * * (中间间隔一个空格)(从后往前分别代表:年 月 日 时 分)这个代表 每天的16点还有个测试:
public class TestT extends TestCase {
T t = new T(); public void testTFail() {
assertFalse(t.t(new Date(), "* 16"));
} public void testTSuccess2() {
assertTrue(t.t(new Date(), "0 16"));
} public void testTSuccess3() {
assertTrue(t.t(new Date(), "0 17 *"));
} public void testTSuccess4() {
assertTrue(t.t(new Date(), "16 10 * *"));
}这个只是部分情况,现在要求就是 我给定时间 跟当前时间比较 相等返回true 不等 返回flase 就是解析字符串跟当前时间比较,大侠们请指点
public boolean t(Date d, String s) {
String[] sa = s.split(" "); //把格式化字符串分割
Calendar c = Calendar.getInstance();
c.setTime(d);
int[] dt = new int[5]; //获取Date对象的年 月 日 时 分
dt[0] = c.get(Calendar.MINUTE);
dt[1] = c.get(Calendar.HOUR_OF_DAY);
dt[2] = c.get(Calendar.DATE);
dt[3] = c.get(Calendar.MONTH) + 1;
dt[4] = c.get(Calendar.YEAR);
boolean result = true;
for (int i=0; i<dt.length && i<sa.length; i++) {
if (sa[i].matches("\\d+")) { //如果格式化字符串是数字
result &= (dt[i]==Integer.valueOf(sa[i]).intValue());
} else (! "*".equals(sa[i])) { //如果格式化字符串不是*号
result = false;
}
}
return result;
}
public static boolean t(Date date,String s) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("mm HH yyyy MM dd");
Date date1 = sdf.parse(s);
return date.getTime()==date1.getTime();
}
但是很显然,当前的时候是包含秒的,很少能和你那个参数只有分的正好相等,所以
我能不能说,你的意思是说分相等的两个时间这里就是相等了?所以可以给你写一个
这样的方法。
public static boolean t(Date date,String s) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("mm HH yyyy MM dd");
Date date1 = sdf.parse(s);
Date date2 = sdf.parse(sdf.format(date));
return date2.getTime()==date1.getTime();
}
OK,希望能帮到你了,
然后判断,如果是数字的字符串就用来和相应的时间比较,比如"0"和相应的分比较,"17"和相应的时比较,"18"和相应的日比较,"*"因为是*号,所以不比较,这样就可以通配*号
当然为了防止有非法字符,比如,"0 17, 8 x y"这样的,那么xy是非法字符,所以匹配失败,也就是代码中else (! "*".equals(sa[i])) 的处理
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DateUtil {
protected static Log logger = LogFactory.getLog(DateUtil.class); // 格式:年-月-日 小时:分钟:秒
public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss"; // 格式:年-月-日 小时:分钟
public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm"; // 格式:年月日 小时分钟秒
public static final String FORMAT_THREE = "yyyyMMdd-HHmmss"; // 格式:年-月-日
public static final String LONG_DATE_FORMAT = "yyyy-MM-dd"; // 格式:月-日
public static final String SHORT_DATE_FORMAT = "MM-dd"; // 格式:小时:分钟:秒
public static final String LONG_TIME_FORMAT = "HH:mm:ss"; //格式:年-月
public static final String MONTG_DATE_FORMAT = "yyyy-MM"; // 年的加减
public static final int SUB_YEAR = Calendar.YEAR; // 月加减
public static final int SUB_MONTH = Calendar.MONTH; // 天的加减
public static final int SUB_DAY = Calendar.DATE; // 小时的加减
public static final int SUB_HOUR = Calendar.HOUR; // 分钟的加减
public static final int SUB_MINUTE = Calendar.MINUTE; // 秒的加减
public static final int SUB_SECOND = Calendar.SECOND; static final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四",
"星期五", "星期六" }; @SuppressWarnings("unused")
private static final SimpleDateFormat timeFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss"); public DateUtil() {
} /**
* 把符合日期格式的字符串转换为日期类型
*/
public static java.util.Date stringtoDate(String dateStr, String format) {
Date d = null;
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
formater.setLenient(false);
d = formater.parse(dateStr);
} catch (Exception e) {
// log.error(e);
d = null;
}
return d;
} /**
* 把符合日期格式的字符串转换为日期类型
*/
public static java.util.Date stringtoDate(String dateStr, String format,
ParsePosition pos) {
Date d = null;
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
formater.setLenient(false);
d = formater.parse(dateStr, pos);
} catch (Exception e) {
d = null;
}
return d;
} /**
* 把日期转换为字符串
*/
public static String dateToString(java.util.Date date, String format) {
String result = "";
SimpleDateFormat formater = new SimpleDateFormat(format);
try {
result = formater.format(date);
} catch (Exception e) {
// log.error(e);
}
return result;
} /**
* 获取当前时间的指定格式
*/
public static String getCurrDate(String format) {
return dateToString(new Date(), format);
} public static String dateSub(int dateKind, String dateStr, int amount) {
Date date = stringtoDate(dateStr, FORMAT_ONE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(dateKind, amount);
return dateToString(calendar.getTime(), FORMAT_ONE);
} /**
* 两个日期相减
* @return 相减得到的秒数
*/
public static long timeSub(String firstTime, String secTime) {
long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
long second = stringtoDate(secTime, FORMAT_ONE).getTime();
return (second - first) / 1000;
} /**
* 获得某月的天数
*/
public static int getDaysOfMonth(String year, String month) {
int days = 0;
if (month.equals("1") || month.equals("3") || month.equals("5")
|| month.equals("7") || month.equals("8") || month.equals("10")
|| month.equals("12")) {
days = 31;
} else if (month.equals("4") || month.equals("6") || month.equals("9")
|| month.equals("11")) {
days = 30;
} else {
if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
|| Integer.parseInt(year) % 400 == 0) {
days = 29;
} else {
days = 28;
}
} return days;
} /**
* 获取某年某月的天数
*/
public static int getDaysOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
} /**
* 获得当前日期
*/
public static int getToday() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DATE);
} /**
* 获得当前月份
*/
public static int getToMonth() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
} /**
* 获得当前年份
*/
public static int getToYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
} /**
* 返回日期的天
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
} /**
* 返回日期的年
*/
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
} /**
* 返回日期的月份,1-12
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
} /**
* 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
*/
public static long dayDiff(Date date1, Date date2) {
return (date2.getTime() - date1.getTime()) / 86400000;
} /**
* 比较两个日期的年差
*/
public static int yearDiff(String before, String after) {
Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(afterDay) - getYear(beforeDay);
} /**
* 比较指定日期与当前日期的差
*/
public static int yearDiffCurr(String after) {
Date beforeDay = new Date();
Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
return getYear(beforeDay) - getYear(afterDay);
}
/**
* 比较指定日期与当前日期的差
*/
public static long dayDiffCurr(String before) {
Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT);
Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
return (currDate.getTime() - beforeDate.getTime()) / 86400000; } /**
* 获取每月的第一周
*/
public static int getFirstWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
c.set(year, month - 1, 1);
return c.get(Calendar.DAY_OF_WEEK);
}
/**
* 获取每月的最后一周
*/
public static int getLastWeekdayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
c.set(year, month - 1, getDaysOfMonth(year, month));
return c.get(Calendar.DAY_OF_WEEK);
} /**
* 获得当前日期字符串,格式"yyyy_MM_dd_HH_mm_ss"
*
* @return
*/
public static String getCurrent() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
StringBuffer sb = new StringBuffer();
sb.append(year).append("_").append(StringUtil.addzero(month, 2))
.append("_").append(StringUtil.addzero(day, 2)).append("_")
.append(StringUtil.addzero(hour, 2)).append("_").append(
StringUtil.addzero(minute, 2)).append("_").append(
StringUtil.addzero(second, 2));
return sb.toString();
} /**
* 获得当前日期字符串,格式"yyyy-MM-dd HH:mm:ss"
*
* @return
*/
public static String getNow() {
Calendar today = Calendar.getInstance();
return dateToString(today.getTime(), FORMAT_ONE);
} /**
* 判断日期是否有效,包括闰年的情况
*
* @param date
* YYYY-mm-dd
* @return
*/
public static boolean isDate(String date) {
StringBuffer reg = new StringBuffer(
"^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
Pattern p = Pattern.compile(reg.toString());
return p.matcher(date).matches();
}
public static void main(String args[]) throws Exception{
Date date = new Date();
System.out.println(t(date,"58 * * * *"));
}
public static boolean t(Date date,String s) {
SimpleDateFormat sdf = new SimpleDateFormat("mm HH dd MM yyyy");
String strDate = sdf.format(date);
String regex = getRegex(s);
Matcher m = Pattern.compile(regex).matcher(strDate);
return m.matches();
}
private static String getRegex(String str){
str = str.replaceAll("\\s+", "\\\\s+?");
str = str.replaceAll("\\*", "\\\\d+?");
return str;
}
}
大哥你这个不对吧?else(! "*".equals(sa[i])){ //如果格式化字符串不是*号
我这老显示错误红叉叉
/*
* 这里是通过替换来拼接正则表达式.
*/
private static String getRegex(String str){
str = str.replaceAll("\\s+", "\\\\s+?");//替换所有[\t\n\r\f]为\s+?
str = str.replaceAll("\\*", "\\\\d+?");//替换所有*为\d+? \d[0-9]
System.out.println("所得正则表达式为 : " + str);
return str;
}
少了个if,不好 意思
else (! "*".equals(sa[i])) 改成
else if (! "*".equals(sa[i]))
Date date = new Date();
System.out.println(t(date,"07 * * * *"));
}
public static boolean t(Date date,String s) {
SimpleDateFormat sdf = new SimpleDateFormat("mm HH dd MM yyyy");
String strDate = sdf.format(date);
System.out.println(strDate);
String regex = getRegex(s);
Matcher m = Pattern.compile(regex).matcher(strDate);
return m.matches();
}
private static String getRegex(String str){
String[] strings = str.split("\\s+");
if(strings.length != 5){
String[] ss = {"*","*","*","*","*"};
for(int i = 0; i < strings.length; i++){
ss[i] = strings[i];
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < ss.length; i++){
if(i == ss.length - 1){
sb.append(ss[i]);
}else{
sb.append(ss[i]).append(" ");
}
}
str = sb.toString();
}
str = str.replaceAll("\\s+", "\\\\s+?");
str = str.replaceAll("\\*", "\\\\d+?");
return str;
}