java 如何在android中比较两个日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14214713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare two date and time in android
提问by Karthikeyan Karthik
I have one problem is there. How to compare 2 date and time
我有一个问题。如何比较2个日期和时间
enter code here
if(fromdate<=nowdt.now() && todate>= nowdt.now()){
////
}
回答by Kevin Bowersox
The java.util.Date object contains methods .before(), .after and .equals() for comparing dates.
java.util.Date 对象包含用于比较日期的方法 .before()、.after 和 .equals()。
if((fromdate.before(nowDt) || fromDate.equals(nowDt))
&& ((todate.after(nowDt) || toDate.equals(nowDt))
////
}
回答by MysticMagic?
A function to compare two date and time:
比较两个日期和时间的函数:
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
}
You can use it where you want to. Result will be > 0 if date1 > date2, = 0 if date1 = date2, < 0 if date1 < date2. Hope it helps.
你可以在你想要的地方使用它。结果将 > 0 如果 date1 > date2,= 0 如果 date1 = date2,< 0 如果 date1 < date2。希望能帮助到你。
回答by Kumar Vivek Mitra
-Use Joda Time library
to do this....
-使用Joda Time library
要做到这一点....
Eg:
例如:
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()));
///////////////////////////// OR
///////////////////////////// 或者
System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
回答by Gridtestmail
Try this one out to find time difference
试试这个找出时差
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();
回答by Peter Lawrey
You can write
你可以写
long nowTime = System.currentTimeMillis();
if(fromdate.getTime() <= nowTime && nowTime <= todate.getTime()) {
or you can write
或者你可以写
Date nowDate = new Date();
if(fromdate.compareTo(nowDate) * nowDate.compareTo(todate) >= 0) {
or
或者
if(!fromdate.after(nowDate) && !todate.before(nowDate))
回答by Karthikeyan Karthik
use this answer
使用这个答案
if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){
do some processs........
}