java 我想要java中两个日期之间的差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13798174/
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-31 14:01:19  来源:igfitidea点击:

I want difference between two date in java?

java

提问by Chand Alam

Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
how to calculate difference between two dates using java

可能的重复:
计算两个 Java 日期实例之间的差异
如何使用 java 计算两个日期之间的差异

I have try to difference two date by using some example but I have not got correct answer.

我试图通过使用一些例子来区分两个日期,但我没有得到正确的答案。

java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
 java.util.Date date1 = df.parse("2012-09-14 15:26:14+00");
 java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
 long diff = Math.abs(date2.getTime() - date1.getTime());
 System.out.println("millisecond="+diff);

I want month difference also but it didnt gave me. It is giving me difference days,hours,minute and seconds but not month.What am i doing wrong? Please help me

我也想要月差,但它没有给我。它给了我不同的天数、小时数、分钟数和秒数而不是月数。我做错了什么?请帮我

Edit:

编辑:

java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
 java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
 java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
 long diff = Math.abs(date2.getTime() - date1.getTime());
 System.out.println(date2.getTime()+"date2");
 System.out.println(date1.getTime()+"date1");
 System.out.println("millisecond="+diff);
 diff=diff/1000;
 System.out.println("second="+diff);
 long days=diff/86400;
 days=days%86400;
 long hours=diff/3600;
 hours=hours%3600;
 long min=diff/60;
 min=min%60;
 hours=(hours-(24*days));
 String time=days+":"+hours+":"+min;
 System.out.println(time);
System.out.println("days="+days+":"+"hours="+hours+":"+"minutes"+min);

This is what i am trying to do.

这就是我想要做的。

回答by Juvanis

You can use Jodatime library for Java. It would be much easier to calculate time-diff between dates with it.

您可以使用Java 的Joda时间库。用它计算日期之间的时间差异会容易得多。

Sample snippet for time-diff:

time-diff 的示例片段

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

回答by Rahul

call it as getDuration(date1, date2, Calendar.MONTH);

将其称为 getDuration(date1, date2, Calendar.MONTH);

 public static long getDuration(Date returnTime, Date leaveTime, int scale) {
        long durationInMillis = returnTime.getTime() - leaveTime.getTime();
        switch (scale) {
            case Calendar.MINUTE:
                return durationInMillis / ONE_MINUTE_IN_MILLIS;
            case Calendar.MILLISECOND:
                return durationInMillis;
            case Calendar.SECOND:
                return durationInMillis / ONE_SECOND_IN_MILLIS;
            case Calendar.HOUR:
                return durationInMillis / ONE_HOUR_IN_MILLIS;
            case Calendar.DAY_OF_YEAR:
            case Calendar.DATE:
                return durationInMillis / ONE_DAY_IN_MILLIS;
            case Calendar.MONTH:
                return durationInMillis / ONE_MONTH_IN_MILLIS; // 30days per month
        }
        throw new IllegalArgumentException("invalid scale specified");
    }

回答by Mark Byers

Date.getTimereturns milliseconds, not seconds. You need to divide by 1000 to get seconds.

Date.getTime返回毫秒,而不是秒。您需要除以 1000 才能获得秒数。

long diff = Math.abs(date2.getTime() - date1.getTime()) / 1000;

Also as mentioned in the comments your format string is incorrect. It should be this:

同样如评论中所述,您的格式字符串不正确。应该是这样的:

"yyyy-MM-dd HH:mm:ss"

回答by T.J. Crowder

The difference you're getting there is the number of millisecondsbetween the two dates, not seconds. Note that the difference between the dates you've given is not a full month.

您在那里获得的差异是两个日期之间的毫秒数,而不是秒数。请注意,您提供的日期之间的差异不是整月。

回答by Evgeniy Dorofeev

To start with let's change yyyy-mm-dd hh:mm:ss to yyyy-MM-dd HH:mm:ss.

首先让我们将 yyyy-mm-dd hh:mm:ss 更改为 yyyy-MM-dd HH:mm:ss。

The difference between dates can be calculated only with Calendar class and below is my Calendar based solution, not sure it's the best one but it is definitely doing its job. It calculates the dates difference in fill months, that is 2012-09-30 15:26:14+00 - 2012-08-30 15:26:14+00 is 1 month. But 2012-09-30 15:26:14+00 - 2012-08-30 15:26:15+00 is 0 month. Note that Locale also matters, because the result depends on light saving setting. I will not comment on it in the hopes that everything is clear from the code

日期之间的差异只能用 Calendar 类计算,下面是我的基于日历的解决方案,不确定它是最好的,但它肯定在做它的工作。它计算填充月份的日期差异,即 2012-09-30 15:26:14+00 - 2012-08-30 15:26:14+00 是 1 个月。但是 2012-09-30 15:26:14+00 - 2012-08-30 15:26:15+00 是 0 个月。请注意,语言环境也很重要,因为结果取决于节光设置。我不会评论它,希望代码中的一切都清楚

public static void main(String[] args) throws Exception {
    java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
    java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
    int diff = getMonthDifference(date1, date2);
    System.out.println(diff);
}

.

.

public static int getMonthDifference(java.util.Date date1, java.util.Date date2) {
    if (date1.after(date2)) {
        return getMonthDifference0(date1, date2);
    } else if (date2.after(date1)) {
        return -getMonthDifference0(date2, date1);
    }
    return 0;
}

.

.

private static int getMonthDifference0(java.util.Date date1, java.util.Date date2) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(date1);
        c2.setTime(date2);
        int diff = 0;
        while (c2.getTimeInMillis() < c1.getTimeInMillis()) {
            c2.add(Calendar.MONTH, 1);
            diff++;
        }
        int dd = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
        if (dd > 0) {
            diff--;
        } else if (dd == 0) {
            int hd = c2.get(Calendar.HOUR_OF_DAY) - c1.get(Calendar.HOUR_OF_DAY);
            if (hd > 0) {
                diff++;
            } else if (hd == 0) {
                long t1 = c1.getTimeInMillis() % (60 * 1000);
                long t2 = c2.getTimeInMillis() % (60 * 1000);
                if (t2 > t1) {
                    diff--;
                }
            }
        }
        return diff;
    }