如果我在Java(Android)(Date1和Date2)中有两个日期,我怎么知道Date2是否在Date1的同一天内? (注意:如果Date2-Date1 <24小时则不行)。一些例子(相同的月份和年份)
Date1: day=14 hour=00:00 Date2: day=14 hour=00:00 --> Result TRUE
Date1: day=13 hour=23:59 Date2: day=14 hour=00:00 --> Result FALSE
Date1: day=14 hour=05:00 Date2: day=14 hour=00:00 --> Result TRUE
Date1: day=14 hour=00:00 Date2: day=15 hour=00:00 --> Result FALSE
由于
答案 0 :(得分:10)
为什么不使用DateUtils
?
您可以直接调用isSameDay等方法
if (DateUtils.isSameDay(date1, date2)) {
System.out.println("Same Date");
} else if (date1.before(date2)) {
System.out.println("date1 before date2");
} else {
System.out.println("date1 after date2");
}
答案 1 :(得分:4)
我从Java: comparing two Dates to see if they are in the same day
复制了此内容Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);