使用joda time api计算两个日期之间的天数[重复]

时间:2022-01-27 16:26:46

This question already has an answer here:

这个问题在这里已有答案:

I have two dates. I am getting dates from database like this:-

我有两个约会。我从这样的数据库中获取日期: -

Date d = new Date();
Date dTarget = finance.getTargetDate();

at the moment my d is 2017-12-29 and dTarget is 2017-12-31

目前我的时间是2017-12-29,dTarget是2017-12-31

Now i am trying to calculate the number of days in between them using Joda time api. I expect number of days to be 2 but at the moment I am getting 1, which I think is incorrect.

现在我正在尝试使用Joda time api计算它们之间的天数。我希望天数为2,但目前我得到1,我认为是不正确的。

My timezone is UTC+5:45

我的时区是UTC + 5:45

     //joda initital datetime
    DateTime intdt = new DateTime(new Date());
    DateTime targetDt = new DateTime(dTarget);

    int noOfDays = Days.daysBetween(intdt,targetDt).getDays();
    System.out.println(noOfDays);

Am I finding the difference between two dates correctly? Why is it not showing 2 for this case?

我能正确找到两个日期之间的差异吗?为什么这个案子没有显示2?

2 个解决方案

#1


2  

Use this

 Days.daysBetween(intdt.toLocalDate(), targetDt.toLocalDate()).getDays() 

The LocalDate class does not store or represent a time or time-zone. Instead, it is a description of the date.

LocalDate类不存储或表示时间或时区。相反,它是对日期的描述。

#2


0  

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

#1


2  

Use this

 Days.daysBetween(intdt.toLocalDate(), targetDt.toLocalDate()).getDays() 

The LocalDate class does not store or represent a time or time-zone. Instead, it is a description of the date.

LocalDate类不存储或表示时间或时区。相反,它是对日期的描述。

#2


0  

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}