我需要计算两个日期之间的天数,而不使用任何库提供的任何日期或日历类。以下是我的想法:
numberOfDays = Math.abs((toYear - fromYear) * 365);
numberOfDays = numberOfDays + Math.abs((toMonth - fromMonth) * 12);
numberOfDays = numberOfDays + Math.abs((toDay - fromDay));
思想?
答案 0 :(得分:1)
在Java 8中,您可以执行以下操作:
long days = ChronoUnit.DAYS.between(LocalDate.of(2014, Month.MARCH, 01), LocalDate.of(2014, Month.FEBRUARY, 15));
答案 1 :(得分:1)
其中一些数字可能为零。
答案 2 :(得分:0)
public class test {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2014, 8, 1, 0, 0, 0);
Date s = cal.getTime();
Date e = new Date();
System.out.println(days(s,e));
}
public static int days(Date start, Date end){
double aTms = Math.floor(start.getTime() - end.getTime());
return (int) (aTms/(24*60*+60*1000));
}
}
答案 3 :(得分:0)
会这样吗?
//get 2 random dates
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = new Date();
Date date2 = sdf.parse("2014-9-12");
final long msInADay = 24*60*60*1000; //turn a day to ms
//divide time difference by the ms of a day
int difference = (int)((date2.getTime() - date1.getTime()) / msInADay);
System.out.println(Math.abs(difference));//Math.abs so you can subtract dates in any order.
更新问题后编辑: 你可以这样做:
static int calcDayDiff(int startY, int startM, int startD, int endY, int endM, int endD){
int result = (startY - endY) * 365;
result += (startM - endM) * 31;
result += (startD - endD);
return Math.abs(result);
}
使用System.out.println(calcDayDiff(2014,9,13,2013,8,12));
进行测试将打印397
请注意,这不是一个非常好的解决方案,因为不是每个月都包含31
天而不是每年365
。您可以通过在方法中添加一些简单逻辑来修复月份日差异,而不是总是乘以31
。由于它是一项任务,我猜你可以考虑每年365
天。