Java,获取两个日期之间的天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7976989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:17:35  来源:igfitidea点击:

Java, get days between two dates

javadate

提问by Hiral Vadodaria

In java, I want to get the number of days between two dates, excluding those two dates.

在java中,我想获得两个日期之间的天数,不包括这两个日期。

For example:

例如:

If first date = 11 November 2011and the second date = 13 November 2011then it should be 1.

如果第一个日期 =11 November 2011和第二个日期 =13 November 2011那么它应该是1.

This is the code I am using but doesn't work (secondDateand firstDateare Calendarobjects):

这是我正在使用但不起作用的代码(secondDate并且firstDateCalendar对象):

long diff=secondDate.getTimeInMillis()-firstDate.getTimeInMillis();
float day_count=(float)diff / (24 * 60 * 60 * 1000);
daysCount.setText((int)day_count+"");                    

I even tried rounding the results but that didn't help.

我什至尝试对结果进行四舍五入,但这没有帮助。

How do I get the number of days between dates in java excluding the days themselves?

如何获得java中日期之间的天数,不包括天数?

回答by slkorolev

I've just tested on SDK 8 (Android 2.2) the following code snippet:

我刚刚在 SDK 8 (Android 2.2) 上测试了以下代码片段:

Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();

date1.clear();
date1.set(
   datePicker1.getYear(),
   datePicker1.getMonth(),
   datePicker1.getDayOfMonth());
date2.clear();
date2.set(
   datePicker2.getYear(),
   datePicker2.getMonth(),
   datePicker2.getDayOfMonth());

long diff = date2.getTimeInMillis() - date1.getTimeInMillis();

float dayCount = (float) diff / (24 * 60 * 60 * 1000);

textView.setText(Long.toString(diff) + " " + (int) dayCount);

it works perfectly and in both cases (Nov 10,2011 - Nov 8,2011) and (Nov 13,2011 - Nov 11,2011) gives dayCount = 2.0

它完美运行,在两种情况下(2011 年 11 月 10 日 - 2011 年 11 月 8 日)和(2011 年 11 月 13 日 - 2011 年 11 月 11 日)都给出了dayCount = 2.0

回答by Eric Leschinski

Get Days between java.util.Dates, ignoring daylight savings time

获取 java.util.Dates 之间的天数,忽略夏令时

Quick and dirty hack:

快速而肮脏的黑客:

public int get_days_between_dates(Date date1, Date date2)
{       
    //if date2 is more in the future than date1 then the result will be negative
    //if date1 is more in the future than date2 then the result will be positive.

    return (int)((date2.getTime() - date1.getTime()) / (1000*60*60*24l));
}

This function will work 99.99% of the time except when it surprises you later on in the edge cases during leap-seconds, daylight savings, timezone changes leap years and the like. If you are OK with the calculation being off by 1 (or 2) hours once in a while, this will suffice.

此功能将在 99.99% 的时间内工作,除非在闰秒、夏令时、时区更改、闰年等边缘情况下让您感到惊讶。如果您认为计算偶尔会偏离 1(或 2)小时,这就足够了。

Get Days between Dates taking into account leapseconds, daylight savings, timezones, etc

考虑闰秒、夏令时、时区等,获取日期之间的天数

If you are asking this question you need to slap yourself. What does it mean for two dates to be at least 1 day apart? It's very confusing. What if one Date is midnight in one timezone, and the other date is 1AM in another timezone? Depending on how you interpret it, the answer is both 1 and 0.

如果你问这个问题,你需要打自己一巴掌。两个日期至少相隔 1 天是什么意思?这很令人困惑。如果一个日期在一个时区是午夜,而另一个日期在另一个时区是凌晨 1 点怎么办?取决于你如何解释它,答案是 1 和 0。

You think you can just force the dates you pass into the above function as Universal time format, that will fix some of your problems. But then you just relocate the problem into how you convert your local time to a universal time. The logical conversion from your timezone to universal time may not be what is intuitive. In some cases you will get a day difference when the dates passed in are obviously two days apart.

您认为您可以将您传递到上述函数的日期强制为通用时间格式,这将解决您的一些问题。但是,您只需将问题重新定位到如何将本地时间转换为世界时间。从您的时区到世界时的逻辑转换可能不是直观的。在某些情况下,当传入的日期明显相隔两天时,您会得到一天的差异。

And you think you can deal with that? There are some retarded Calendar systems in the world which are constantly changing depending on the harvest season and installed political rulers. If you want to convert their time to UTC, java.util.Date is going to fail you at the worst moment.

你认为你能解决这个问题吗?世界上有一些迟钝的日历系统,它们根据收获季节和已安装的统治者不断变化。如果您想将它们的时间转换为 UTC,java.util.Date 将在最糟糕的时刻让您失望。

If you need to calculate the days between dates and it is critical that everything come out right, you need to get an external library called Joda Time: (They have taken care of all the details for you, so you can stay blissfully unaware of them): http://joda-time.sourceforge.net/index.html

如果您需要计算日期之间的天数并且一切都正确至关重要,您需要获得一个名为 Joda Time 的外部库:(他们已经为您处理了所有细节,因此您可以幸福地不知道它们): http://joda-time.sourceforge.net/index.html

回答by Vladimir

I have two suggestions:

我有两个建议:

  1. Make sure your float day_countis calculated correctly

    float day_count = ((float)diff) / (24f * 60f * 60f * 1000f);

  2. If it's rounding error, try using floormethod

    daysCount.setText("" + (int)Math.floor(day_count));

  1. 确保您float day_count的计算正确

    float day_count = ((float)diff) / (24f * 60f * 60f * 1000f);

  2. 如果是舍入错误,请尝试使用floor方法

    daysCount.setText("" + (int)Math.floor(day_count));

回答by Aaron Digulla

  1. Don't use floats for integer calculations.

  2. Are you sure your dates are days? The precision of the Datetype is milliseconds. So the first thing you need to do is round the date to something which doesn't have hours. Example: It's just one hour from 23:30 2011-11-01to 00:30 2011-11-02but the two dates are on different days.

  1. 不要使用浮点数进行整数计算。

  2. 你确定你的日期是天吗?该Date类型的精度为毫秒。因此,您需要做的第一件事是将日期四舍五入为没有小时的日期。示例:距23:30 2011-11-01至仅一小时,00:30 2011-11-02但两个日期在不同的日子。

回答by DuncanKinnear

If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:

如果您只打算处理 1900 年到 2100 年之间的日期,则有一个简单的计算方法可以为您提供自 1900 年以来的天数:

public static int daysSince1900(Date date) {
    Calendar c = new GregorianCalendar();
    c.setTime(date);

    int year = c.get(Calendar.YEAR);
    if (year < 1900 || year > 2099) {
        throw new IllegalArgumentException("daysSince1900 - Date must be between 1900 and 2099");
    }
    year -= 1900;
    int month = c.get(Calendar.MONTH) + 1;
    int days = c.get(Calendar.DAY_OF_MONTH);

    if (month < 3) {
        month += 12;
        year--;
    }
    int yearDays = (int) (year * 365.25);
    int monthDays = (int) ((month + 1) * 30.61);

    return (yearDays + monthDays + days - 63);
}

Thus, to get the difference in days between two dates, you calculate their days since 1900 and calc the difference. Our daysBetween method looks like this:

因此,要获得两个日期之间的天数差异,您可以计算它们自 1900 年以来的天数并计算差异。我们的 daysBetween 方法如下所示:

public static Integer getDaysBetween(Date date1, Date date2) {
    if (date1 == null || date2 == null) {
        return null;
    }

    int days1 = daysSince1900(date1);
    int days2 = daysSince1900(date2);

    if (days1 < days2) {
        return days2 - days1;
    } else {
        return days1 - days2;
    }
}

In your case you would need to subtract an extra day (if the days are not equal).

在您的情况下,您需要减去额外的一天(如果天数不相等)。

And don't ask me where this calculation came from because we've used it since the early '90s.

不要问我这个计算是从哪里来的,因为我们从 90 年代初就开始使用它了。