我需要在两个joda日期之间获得几天,几个月和几年的确切差异。我使用下面的代码:
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, ");
然而,我需要得到确切的年份而不是2年,我应该得到2010,2011 或者代替18个月(涵盖所有月份),我需要得到1到12之间的范围。
首先,我想更改此代码以便我可以使用Java 8时间,那么如何使用Java 8时间呢?
答案 0 :(得分:0)
您可以保留一份清单并根据您的差异填写清单。我已经实施了一个年度案例的方法来提出一个想法:
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;
}
总的来说,创建2022年和2017年的简单日期,例如:
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();
将以下行添加到主页时:
yearLister(yearCount, startingYear, endYear);
输出为:[2018,2019,2020,2021]