Java 如何在android中比较两个日期和时间
我有一个问题。如何比较两个日期和时间Java 如何在android中比较两个日期和时间,java,android,Java,Android,我有一个问题。如何比较两个日期和时间 enter code here if(fromdate<=nowdt.now() && todate>= nowdt.now()){ //// } 在此处输入代码 如果(fromdate=nowdt.now()){ //// } java.util.Date对象包含用于比较日期的方法.before()、.after()和.equals() if((fromdate.before(nowDt) || fromDate.equal
enter code here
if(fromdate<=nowdt.now() && todate>= nowdt.now()){
////
}
在此处输入代码
如果(fromdate=nowdt.now()){
////
}
java.util.Date对象包含用于比较日期的方法.before()、.after()和.equals()
if((fromdate.before(nowDt) || fromDate.equals(nowDt))
&& ((todate.after(nowDt) || toDate.equals(nowDt))
////
}
用于比较两个日期和时间的函数:
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
Joda时间库
来完成此操作
例如:
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();
你可以写
long nowTime = System.currentTimeMillis();
if(fromdate.getTime() <= nowTime && nowTime <= todate.getTime()) {
Date nowDate = new Date();
if(fromdate.compareTo(nowDate) * nowDate.compareTo(todate) >= 0) {
或
用这个答案
if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){
do some processs........
}
你可能想解释为什么?我知道这是一个相对古老的答案,但为什么不只是返回日期1.比较(日期2)?这难道不会产生同样的结果吗?
if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){
do some processs........
}