获取两个joda日期之间的确切年,天或月 [英] Getting the exact years or days or months between two joda date

查看:141
本文介绍了获取两个joda日期之间的确切年,天或月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获得两个joda日期时间之间在天数,月数和年数方面的确切差异.我正在使用以下代码:

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, ");

但是,我需要得到确切的年份,而不是2年,我应该得到2010,2011 或代替18个月(涵盖所有月份),我需要使范围介于1到12之间.

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.

首先,我想更改此代码,以便可以使用Java 8 time,那么如何使用Java 8 time呢?

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

推荐答案

您可以保留一个列表并根据您的不同来填写它.我已经针对年份案例实现了一种方法:

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;
    }

例如,主要创建2022年和2017年的简单日期,

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);

输出为:[2018、2019、2020、2021]

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

这篇关于获取两个joda日期之间的确切年,天或月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆