我有一个问题。如何比较2个日期和时间
enter code here
if(fromdate<=nowdt.now() && todate>= nowdt.now()){
////
}
java.util.Date 对象包含用于比较日期的方法 .before()、.after 和 .equals()。
if((fromdate.before(nowDt) || fromDate.equals(nowDt))
&& ((todate.after(nowDt) || toDate.equals(nowDt))
////
}
-用来Joda Time library
做这个......
例如:
Date ds = new Date();
DateTime d = new DateTime(ds);
DateTime e = new DateTime(2012,12,07, 0, 0);
System.out.println(d.isEqual(e));
System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));
///////////////////////////// 或者
System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
试试这个找出时差
Calendar Day = Calendar.getInstance();
Day.set(Calendar.DAY_OF_MONTH,25);
Day.set(Calendar.MONTH,7);
Day.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - Day.getTimeInMillis();
使用这个答案
if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){
do some processs........
}
你可以写
long nowTime = System.currentTimeMillis();
if(fromdate.getTime() <= nowTime && nowTime <= todate.getTime()) {
或者你可以写
Date nowDate = new Date();
if(fromdate.compareTo(nowDate) * nowDate.compareTo(todate) >= 0) {
或者
if(!fromdate.after(nowDate) && !todate.before(nowDate))
比较两个日期和时间的函数:
public static int compareTwoDates(Date date1, Date date2) {
if (date1 != null && date2 != null) {
int retVal = date1.compareTo(date2);
if (retVal > 0)
return 1; // date1 is greatet than date2
else if (retVal == 0) // both dates r equal
return 0;
}
return -1; // date1 is less than date2
}
你可以在你想用的地方使用它。如果 date1 > date2,则结果将 > 0,如果 date1 = date2,则 = 0,如果 date1 < date2,则 < 0。希望能帮助到你。