我想有一个compareTo方法来忽略java.util.Date的时间部分。我想有很多方法可以解决这个问题。最简单的方法是什么?
当前回答
如果你正在寻找一个简单的解决方案,但你不想从你的项目中更改已弃用的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
}
`
其他回答
这里有一个来自这个博客的解决方案: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.");
也就是说,你可以看到以毫秒为单位的时间差是否小于一天的长度。
如果严格使用Date (java.util.Date),或者不使用任何外部库。用这个:
public Boolean compareDateWithoutTime(Date d1, Date d2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(d1).equals(sdf.format(d2));
}
如果你真的想使用java.util。约会时,你会这样做:
public class TimeIgnoringComparator implements Comparator<Date> {
public int compare(Date d1, Date d2) {
if (d1.getYear() != d2.getYear())
return d1.getYear() - d2.getYear();
if (d1.getMonth() != d2.getMonth())
return d1.getMonth() - d2.getMonth();
return d1.getDate() - d2.getDate();
}
}
或者,使用Calendar代替(首选,因为getYear()等已弃用)
public class TimeIgnoringComparator implements Comparator<Calendar> {
public int compare(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR))
return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH))
return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
return c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
}
}
DateUtil.daysBetween()怎么样?它是Java,它返回一个数字(以天为单位)。
我更倾向于直接使用Joda库而不是java.util.Date,因为Joda区分了日期和时间(参见YearMonthDay和DateTime类)。
然而,如果你确实希望使用java.util.Date,我建议写一个实用方法;如。
public static Date setTimeToMidnight(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime( date );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
推荐文章
- 在流中使用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