java Java方法以年,月和日为单位查找2个日期对象之间的差异

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

Java method to find difference between 2 date objects in years, months and days

java

提问by Vidya

I have a start date and end date. the duration between the 2 dates should be in the form of years, months and days. I am new to java. When I run the below method the out I get is 0 years, 12 months 1 days. Please suggest an alternative to get accurate difference in years, months and days.

我有一个开始日期和结束日期。两个日期之间的持续时间应为年、月和日的形式。我是 Java 新手。当我运行以下方法时,我得到的结果是 0 年 12 个月 1 天。请提出一种替代方法来获得年、月和日的准确差异。

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Duration {

    private String getAssignmentDuration(java.util.Date oldDate, java.util.Date newDate) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        if (oldDate.compareTo(newDate) > 0) {
            c1.setTime(newDate);
            c2.setTime(oldDate);
        } else {
            System.out.println("invalid");
            return "Invalid selection";

        }
        int year = 0;
        int month = 0;
        int days = 0;
        boolean doneMonth = false;
        boolean doneYears = false;
        while (c1.before(c2)) {
            //log.debug("Still in Loop");
            if (!doneYears) {
                c1.add(Calendar.YEAR, 1);
                year++;
            }
            if (c1.after(c2) || doneYears) {
                if (!doneYears) {
                    doneYears = true;
                    year--;
                    c1.add(Calendar.YEAR, -1);
                }   
                if (!doneMonth) {
                    c1.add(Calendar.MONTH, 1);
                    month++;
                }
                if (c1.after(c2) || doneMonth) {
                    if (!doneMonth) {
                        doneMonth = true;
                        month--;
                        c1.add(Calendar.MONTH, -1);
                    }

                    c1.add(Calendar.DATE, 1);
                    days++;
                    if (c1.after(c2)) {
                        days--;
                    }
                    // this will not be executed
                    if (days == 31 || month==12) {
                        break;
                    }
                }
            }
        }
        System.out.println(year + " years, " + month + " months, " + days + " days");
        return year + " years, " + month + " months, " + days + " days";

    }


    public static void main(String[] args) {
        Duration d1= new Duration();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        java.util.Date oldDate = null;
        try {
            oldDate = sdf.parse("2012/08/29");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        java.util.Date newDate = null;
        try {
            newDate = sdf.parse("2013/08/31");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        d1.getAssignmentDuration(oldDate, newDate);
    }

}

回答by user2640848

 public static String getDateDifferenceInDDMMYYYY(Date from, Date to) {
        Calendar fromDate=Calendar.getInstance();
        Calendar toDate=Calendar.getInstance();
        fromDate.setTime(from);
        toDate.setTime(to);
        int increment = 0;
        int year,month,day;
        System.out.println(fromDate.getActualMaximum(Calendar.DAY_OF_MONTH));
        if (fromDate.get(Calendar.DAY_OF_MONTH) > toDate.get(Calendar.DAY_OF_MONTH)) {
            increment =fromDate.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
         System.out.println("increment"+increment);
// DAY CALCULATION
        if (increment != 0) {
            day = (toDate.get(Calendar.DAY_OF_MONTH) + increment) - fromDate.get(Calendar.DAY_OF_MONTH);
            increment = 1;
        } else {
            day = toDate.get(Calendar.DAY_OF_MONTH) - fromDate.get(Calendar.DAY_OF_MONTH);
        }

// MONTH CALCULATION
        if ((fromDate.get(Calendar.MONTH) + increment) > toDate.get(Calendar.MONTH)) {
            month = (toDate.get(Calendar.MONTH) + 12) - (fromDate.get(Calendar.MONTH) + increment);
            increment = 1;
        } else {
            month = (toDate.get(Calendar.MONTH)) - (fromDate.get(Calendar.MONTH) + increment);
            increment = 0;
        }

// YEAR CALCULATION
        year = toDate.get(Calendar.YEAR) - (fromDate.get(Calendar.YEAR) + increment);
     return   year+"\tYears\t\t"+month+"\tMonths\t\t"+day+"\tDays";
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(1999,01,8);
       /*  Calendar calendar1 = Calendar.getInstance();
        calendar1.set(2012,01,23);*/
        System.out.println(getDateDifferenceInDDMMYYYY(calendar.getTime(),new Date()));
    }

回答by dan

Joda Time has a concept of time Intervalthat you can use, like:

Joda Time 有一个您可以使用的时间间隔概念,例如:

Interval interval = new Interval(oldDate.getTime(), newDate.getTime());

Then using a Periodobject, like:

然后使用Period对象,例如:

Period period = interval.toPeriod().normalizedStandard(PeriodType.yearMonthDay());

PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendYears()
            .appendSuffix(" year ", " years ")
            .appendSeparator(" and ")
            .appendMonths()
            .appendSuffix(" month ", " months ")
            .appendSeparator(" and ")
            .appendDays()
            .appendSuffix(" day ", " days ")
            .toFormatter();
System.out.println(formatter.print(period));

You will easily be able to print your diference in years and months.

您将能够轻松地打印出以年和月为单位的差异。

Probably you changes something while posting the question, because to fix your code (note that I didn't tested if your code will work with all sort of ranges), you only need to properly initialize the Calendar objects and the reverse the invalid selection check:

可能您在发布问题时更改了某些内容,因为要修复您的代码(请注意,我没有测试您的代码是否适用于所有类型的范围),您只需要正确初始化 Calendar 对象并反转无效的选择检查:

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
if (oldDate.compareTo(newDate) < 0) {
    c2.setTime(newDate);
    c1.setTime(oldDate);
} else {
    System.out.println("invalid");
    return "Invalid selection";
}

回答by smttsp

Assume you have Date date1, date2and they are initialized where date1>date2.

假设您有Date date1, date2并且它们在 where 处被初始化date1>date2

long diff = date1.getTime() - date2.getTime(); //this is going to give you the difference in milliseconds

Date result = new Date(diff);
Format frmt = new SimpleDateFormat("yy MM dd HH:mm:ss");
return frmt.format(result).toString();//or if you want system.out.println(...);

回答by Basil Bourque

tl;dr

tl;博士

Period.between( 
    LocalDate.of( 2017 , Month.JANUARY , 23 ) , 
    LocalDate.of( 2017 , Month.MARCH , 27 ) 
)

Call:

称呼:

.getYears()
.getMonths()
.getDays()

Avoid legacy date-time classes

避免遗留的日期时间类

You are use troublesome old date-time classes, now legacy, supplanted by java.time classes.

你正在使用麻烦的旧日期时间类,现在是遗留的,被 java.time 类取代。

Using java.time

使用 java.time

The LocalDateclass represents a date-only value without time-of-day and without time zone.

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

today.toString(): 2017-05-05

today.toString(): 2017-05-05

For our example, we create another LocalDate.

对于我们的示例,我们创建另一个LocalDate.

LocalDate earlier = today.minusMonths( 2 ).minusWeeks( 3 ).minusDays( 2 ) ;

earlier.toString(): 2017-02-10

早先.toString(): 2017-02-10

To represent a span of time unattached to the timeline in the granularity of years-month-days, use the Periodclass.

要以年-月-日的粒度表示未附加到时间线的时间跨度,请使用Period该类。

Period p = Period.between( earlier , today ) ;
int years = p.getYears();
int months = p.getMonths();
int days = p.getDays();

See this code run live at IdeOne.com.

在 IdeOne.com 上查看此代码的实时运行情况

ISO 8601

ISO 8601

The ISO 8601standard defines formats for textual representations of date-time values. For durations of years-months-days, the pattern is PnYnMnDTnHnMnSwhere Pmarks the beginning and Tseparates the years-months-days portion from the hours-minutes-seconds portion.

ISO 8601标准定义格式的日期时间值的文本表示。对于年,月,日的持续时间,该模式是PnYnMnDTnHnMnS其中P标记开始和T分离小时-分-秒部分的年,月,日部分。

The java.time classes use the standard formats by default when parsing/generating strings. The Periodclass generates this particular pattern in its toStringmethod.

java.time 类在解析/生成字符串时默认使用标准格式。的Period类生成在其这个特定的图案toString的方法。

String output = p.toString() ;

p.toString(): P2M25D

p.toString(): P2M25D

回答by Bhushankumar Lilapara

    long diff = today.getTimeInMillis() - birth.getTimeInMillis();


    // Calculate difference in seconds
    long Seconds = diff / 1000;

    // Calculate difference in minutes
    long Minutes = diff / (60 * 1000);

    // Calculate difference in hours
    long Hours = diff / (60 * 60 * 1000);

    // Calculate difference in days
    long Days = diff / (24 * 60 * 60 * 1000);

    long Months = diff / (24 * 60 * 60 * 12 * 1000);

    //lblTsec, lblTmint, lblthours,lblTdays;
    System.out.println("Seconds : " + Seconds + "");
    System.out.println("Minutes : " + Minutes + "");
    System.out.println("Hours : " + Hours + "");
    System.out.println("Days : " + Days + "");

回答by Thirumaran

Simply you could calculate difference between two dates milliseconds and divide by seconds, minutes, hours, days and month

只需计算两个日期之间的差异毫秒,然后除以秒、分钟、小时、天和月

suppose you want to get difference between years try this,

假设你想得到年份之间的差异试试这个,

public int findDiff(Date fromDate, Date toDate) {

    if(fromDate == null || toDate == null) {
        return -1;
    }

    long diff = toDate.getTime() - fromDate.getTime();

    int diffInYears = (int) (diff / (60 * 60 * 1000 * 24 * 30.41666666 * 12));
    return diffInYears;
}

suppose you want difference between months remove 12(means months) from the divider. likewise you can get days, hours, minutes..

假设您希望月份之间的差异从分隔符中删除 12(表示月份)。同样,您可以获得天,小时,分钟..

回答by Joji George

public static long[] differenceBetweenDates(Date fromDate, Date toDate) {
    Calendar startDate = Calendar.getInstance();
    startDate.setTime(fromDate);
    long years = 0;
    long months = 0;
    long days = 0;
    Calendar endDate = Calendar.getInstance();
    endDate.setTime(toDate);
    Calendar tmpdate = Calendar.getInstance();
    tmpdate.setTime(startDate.getTime());

    tmpdate.add(Calendar.YEAR, 1);
    while (tmpdate.compareTo(endDate) <= 0) {
        startDate.add(Calendar.YEAR, 1);
        tmpdate.add(Calendar.YEAR, 1);
        years++;
    }
    tmpdate.setTime(startDate.getTime());
    tmpdate.add(Calendar.MONTH, 1);
    while (tmpdate.compareTo(endDate) <= 0) {
        startDate.add(Calendar.MONTH, 1);
        tmpdate.add(Calendar.MONTH, 1);
        months++;
    }
    tmpdate.setTime(startDate.getTime());
    tmpdate.add(Calendar.DATE, 1);
    while (tmpdate.compareTo(endDate) <= 0) {
        startDate.add(Calendar.DATE, 1);
        tmpdate.add(Calendar.DATE, 1);
        days++;
    }
    return new long[]{days, months, years};
}