一、需求
在网上看到用SimpleDateFormat类计算相差天数
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
/*天数差*/
Date fromDate1 = simpleFormat.parse("2018-03-01 12:00");
Date toDate1 = simpleFormat.parse("2018-03-12 12:00");
long from1 = fromDate1.getTime();
long to1 = toDate1.getTime();
int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24));
System.out.println("两个时间之间的天数差为:" + days);
因为我只是计算日期间相差多少天,可是用这个方法,如果没有满24小时,相差的天数就不算一天,这就不符合我的要求
后来,我知道了ChronoUnit类,用LocalDate来计算天数
LocalDate不包括时间,只是单纯的年月日
二、实现步骤
方法一:
(这个方法只能在Android8以上才能用)
选择一个Date类型的年月日,将其转化成对应的LocalDate,然后用LocalDate.now获取今天的年月日,接着用ChronoUnit.DAYS.between(startDate, endDate);
来计算
这是endDate减去starDate,
val todayLocalDate = LocalDate.now()
//获取日期框中localdate的值
val selectLocalDate = CustomDateFormat.dateToLocalDate(tvDate)
//如:选中10月30日,今日为10月29日,则选中减去今日,差值为1
val differDays= ChronoUnit.DAYS.between(todayLocalDate,selectLocalDate).toInt()
@RequiresApi(Build.VERSION_CODES.O)
fun dateToLocalDate(date: Date): LocalDate {
val instance = date.toInstant()
val zoneId = ZoneId.systemDefault()
return instance.atZone(zoneId).toLocalDate()
}
方法二:
将日期后面的时间全设为0点,这样就不会有不满二十四小时无法算一天的情况了
//某天到今天共有多少天(某天,今天都算在内)
public static int intervalsDates(String dateString2) {
Date date = Calendar.getInstance().getTime();
java.text.DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(format.format(date)+" 00:00:00");
date2 = format.parse(dateString2+" 00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
long interval = (date2.getTime() - date1.getTime()) / (1000*3600*24);
if (interval<0){
interval = interval*(-1);
}
int dates = (int) (interval+1);
return dates;
}