两个日期之间的天数

4
我被分配了一个任务,需要计算两个给定日期之间的天数,并发现了一个非常奇怪的结果(2127天)作为第三行输入,这似乎是正确的,但是此任务要求的输出结果是另一种不同的结果(1979天)。我查看了此篇文章 Calculate the number of days between two dates 以及其他几篇文章,并按照建议使用了Joda库得到了2127天的结果。
问题:给定两个日期(在1901年至2999年期间,包括1901和2999),找出两个日期之间的天数。
输入:六组数据。每组数据包含两个日期,格式为月、日、年。例如,“6,2,1983,6,22,1983”表示从1983年6月2日到1983年6月22日。
输出:给定日期之间的天数,不包括开始日期和结束日期。例如,1983年6月2日与1983年6月22日之间有19天;即6月3日、4日…21日。
样例输入(3组):
 Input Line #1:  6, 2, 1983, 6, 22, 1983
 Output #1:  19

Input Line #2:  7, 4, 1984, 12, 25, 1984
 Output #2:  173

 Input Line #3:  1, 3, 1989, 3, 8, 1983
 Output #3:  1979 

这是我的解决方案。
private boolean isYearValid(int year){
    return year >=1901 && year <= 2999;
}

public int numOfDays(String dates){
    Calendar date1 = new GregorianCalendar();
    Calendar date2 = new GregorianCalendar();
    String [] dateSplit = dates.split(",");
    int len = dateSplit.length;
    int year = 0;
    for(int i=0;i<len;i++){
        dateSplit[i]=dateSplit[i].trim();
        if(i==2||i==5){
            try {
                year = Integer.parseInt(dateSplit[i]);
            }
            catch (NumberFormatException e){
                throw new IllegalArgumentException(String.format("Usage: Year input %s is not valid",dateSplit[i]));
            }
            if(!isYearValid(year))
                throw new IllegalArgumentException("Usage: Year of date should be between the years 1901 and 2999, inclusive");
        }
    }
    int [] d = new int[6];

    for(int i=0;i<6;i++)
        try {
            d[i]=Integer.parseInt(dateSplit[i]);
        }
    catch(NumberFormatException e){
        throw new IllegalArgumentException("Usage: Date entered is not valid");
    }
    date1.set(d[2], d[0],d[1]);
    date2.set(d[5], d[3], d[4]);
    long milli1= date1.getTimeInMillis();
    long milli2 = date2.getTimeInMillis();
    long diff;
    if(milli1>milli2){
        diff = milli1 - milli2;
    }
    else{
        diff = milli2 - milli1;
    }
    return (int) (diff / (24 * 60 * 60 * 1000))-1;
}

解决 - 看起来测试数据有误,因为1, 3, 1989, 8, 3, 1983的结果应该是1979天。

这是一个给我的练习,但我认为我已经解决了问题,因为1、3、1989、8、3、1983产生了1979天。看起来给我的测试数据是不正确的。 - unleashed
还有一件事我不确定你是否考虑到了,Calendar.set(int,int,int) 方法中的月份是从0开始计算的。所以六月对应的是5 - Jon Lin
2个回答

2

出于好奇,这是作业吗?如果不是,为什么不使用Joda-Time库来完成这项工作。它会处理月份的长度、闰年等问题...

    DateTime dt1 = ...;
    DateTime dt2 = ...;
    Duration duration = new Duration(dt1, dt2);
    long days = duration.getStandardDays();

2

这个答案为什么不正确,值得被踩吗?请解释一下。 - Tomasz Nurkiewicz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接