如何在java中比较两个日期? [英] how to compare two dates in java?
本文介绍了如何在java中比较两个日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个日期在一起,我只想比较日期部分而不是时间部分这是我如何存储日期在我的程序:
I'm trying to compare two dates together and I only want to compare the date part not the time part this is how I store date inside my program :
Thu Jan 27 23:20:00 GMT 2011
a:
I have an:
ArrayList<Date> dateList;
,我想使用
dateList.compares(newDate);
// if the answer was false which means I
// have new date then add the newdate to my list
但是由于时间部分也涉及我不能得到正确的答案。
我如何解决我的问题?
but since the time part also is involved I can't get the proper answer. How can I fix my problem?
我不想使用JODA-TIME
I don't want use JODA-TIME
推荐答案
您可以通过这样的值比较价值
You can compare value by value like this
d1.getDate().equals(d2.getDate()) &&
d1.getYear().equals(d2.getYear()) &&
d1.getMonth().equals(d2.getMonth())
p>
Or
Date date1 = new Date(d1.getYear(), d1.getMonth(), d1.getDate());
Date date2 = new Date(d2.getYear(), d2.getMonth(), d2.getDate());
date1.compareTo(date2);
如果您使用Date类,请考虑使用Calendar类
这是最优雅的解决方案,使用日历和比较器为此
If you work with Date class, consider using Calendar class instead Here's the most elegant solution, using Calendar and Comparator for this
public class CalendarDateWithoutTimeComparator implements Comparator<Calendar> {
public int compare(Calendar cal1, Calendar cal2) {
if(cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)) {
return cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
} else if (cal1.get(Calendar.MONTH) != cal2.get(Calendar.MONTH)) {
return cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
}
return cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH);
}
}
用法:
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
// these calendars are equal
CalendarDateWithoutTimeComparator comparator = new CalendarDateWithoutTimeComparator();
System.out.println(comparator.compare(c1, c2));
List<Calendar> list = new ArrayList<Calendar>();
list.add(c1);
list.add(c2);
Collections.sort(list, comparator);
这篇关于如何在java中比较两个日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文