我想有一个compareTo方法来忽略java.util.Date的时间部分。我想有很多方法可以解决这个问题。最简单的方法是什么?
当前回答
这里有一个来自这个博客的解决方案:http://brigitzblog.blogspot.com/2011/10/java-compare-dates.html
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in days: " + diffDays + " days.");
也就是说,你可以看到以毫秒为单位的时间差是否小于一天的长度。
其他回答
我不知道这是新的想法或其他,但我给你展示我所做的
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date td_date = new Date();
String first_date = dtf.format(td_date); //First seted in String
String second_date = "30/11/2020"; //Second date you can set hear in String
String result = (first_date.equals(second_date)) ? "Yes, Its Equals":"No, It is not Equals";
System.out.println(result);
我的建议:
Calendar cal = Calendar.getInstance();
cal.set(1999,10,01); // nov 1st, 1999
cal.set(Calendar.AM_PM,Calendar.AM);
cal.set(Calendar.HOUR,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
// date column in the Thought table is of type sql date
Thought thought = thoughtDao.getThought(date, language);
Assert.assertEquals(cal.getTime(), thought.getDate());
我也更喜欢Joda Time,但这里有一个替代方案:
long oneDay = 24 * 60 * 60 * 1000
long d1 = first.getTime() / oneDay
long d2 = second.getTime() / oneDay
d1 == d2
EDIT
我把UTC的东西放在下面,以防你需要比较UTC以外的特定时区的日期。如果你确实有这样的需求,那么我真的建议你去找Joda。
long oneDay = 24 * 60 * 60 * 1000
long hoursFromUTC = -4 * 60 * 60 * 1000 // EST with Daylight Time Savings
long d1 = (first.getTime() + hoursFromUTC) / oneDay
long d2 = (second.getTime() + hoursFromUTC) / oneDay
d1 == d2
如果你正在寻找一个简单的解决方案,但你不想从你的项目中更改已弃用的java.util.Date类,你可以将这个方法添加到你的项目中,并继续你的探索:
使用java.util.concurrent.TimeUnit
`
public boolean isSameDay(Date first, Date second) {
long difference_In_Time = first.getTime() - second.getTime();
// calculate difference in days
long difference_In_Days =
TimeUnit
.MILLISECONDS
.toDays(difference_In_Time);
if (difference_In_Days == 0) {
return true;
}
return false;
}
`
像这样实现它:
`
Date first = ...;
Date second = ...;
if (isSameDay(first, second)) {
// congratulations, they are the same
}
else {
// heads up champ, they are not the same
}
`
如果你只想比较两个没有时间的日期,那么下面的代码可能会帮助你:
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date dLastUpdateDate = dateFormat.parse(20111116);
Date dCurrentDate = dateFormat.parse(dateFormat.format(new Date()));
if (dCurrentDate.after(dLastUpdateDate))
{
add your logic
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 解析日期字符串并更改格式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder