Getting the exact years or days or months between two joda date [duplicate]

岁酱吖の 提交于 2019-12-12 06:02:29

问题


I need to get the exact difference in terms of days and months and years between two joda date time. I am using the code below:

DateTime jodaStartTime=new DateTime(startTime);
DateTime jodaEndTime=new DateTime(endTime);

Period period = new Period(jodaStartTime, jodaEndTime);

System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");

However, I need to get exact years for example instead of 2 years, I shoud get 2010,2011 or instead of 18 months (covering all months), I need to get the range between 1 to 12.

First, I want to change this code so I can use Java 8 time, so how to do that with Java 8 time?


回答1:


You can keep a list and fill it depending on the difference you have. I have implemented a method as for year case to give an idea:

private static LinkedList yearLister(int yearCount, int startingYear, int endYear){
    LinkedList years = new LinkedList();
    if (yearCount < 0){ yearCount = -yearCount; } 
    // yearCount can be negative. 
    // When that is the case, you won't be able to add elements to your   
    // list. This statement deals with that.

    if(startingYear > endYear){         
        for(int i = 0; i < yearCount; i++){
            years.add(endYear + i + 1 );
        }
    } else if (startingYear < endYear) {            
        for(int i = 0; i < yearCount - 1; i++){
            years.add(startingYear + i + 1);
            }
        }

    System.out.println(years);
    return years;
    }

In the main, with creating simple dates for years 2022 and 2017, for example:

Date d1,d2 = null; // need these for formatting
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");

String dateStart = "01/01/2022 05:30";
String dateStop = "02/2/2017 06:31";            
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

DateTime jodaStartTime=new DateTime(d1);
DateTime jodaEndTime=new DateTime(d2);

int startingYear = jodaStartTime.getYear();
int endYear = jodaEndTime.getYear();

When you add the following line to the main:

yearLister(yearCount, startingYear, endYear);

The output is: [2018, 2019, 2020, 2021]



来源:https://stackoverflow.com/questions/43795066/getting-the-exact-years-or-days-or-months-between-two-joda-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!