1. 程式人生 > >java 日期判斷 給定日期是否為當天 一週7天以內 一週7天以外

java 日期判斷 給定日期是否為當天 一週7天以內 一週7天以外

public static boolean isToday(String validateDate){
final String format = "yyyy-MM-dd HH:mm:ss";
Date vDate  = null;
try {
vDate = str2Date(validateDate,format);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
Date today = new Date();
today.setHours(23);
today.setMinutes(59);
today.setSeconds(59);
long diff = today.getTime()-vDate.getTime();
if(diff<0){
return false;
}else{
long days = diff/(1000*60*60*24); 
if(days==0){
return true;
}else{
return false;
}
}

}

/**
*距離當前時間七天之內的日期,和七天之外的日期
* @param dt
* @param type 
* type:1--7天之內的 
* type:2--7天之外的
* @return
*/
public static boolean getDayDiffFromToday(Date dt,int type){
Date today=new Date();
today.setHours(23);
today.setMinutes(59);
today.setSeconds(59);


long diff = today.getTime() - dt.getTime();
if(diff<0)diff=0;
long days = diff/(1000*60*60*24);


if(type==1 && days>0 && days<=7)return true;
if(type==2 && days>7)return true;


return false;


/**
* 將string 按指定格式轉化為java.util.Date

* @param str
* @param format
* @return
* @throws ParseException
*/
public static Date str2Date(String str, String format)
throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return (Date) sdf.parse(str);
}