Difference in Days between two Java dates?

2019-02-14 13:47发布

I want to get the difference between two Java Date objects. I've used Joda-Time library. But the problem is that I'm getting the Days greater difference than that of actual day difference.

Here's my code snippet:

DateFormat formatter = new SimpleDateFormat("mm/dd/yyyy");

Date someDate=new Date();
Date today = Calendar.getInstance().getTime();

try     {
    someDate = formatter.parse("06/22/2010");
}
catch(ParseException pe)    {
    System.out.println("Parser Exception");
}

int days = Days.daysBetween(new DateTime(someDate), new DateTime(today)).getDays();

System.out.println(" Days Between " + someDate + " : " + today + " - " + days);

Here's my output:

 Days Between Fri Jan 22 00:06:00 IST 2010 : Sun Jul 25 19:27:01 IST 2010 - 184

Here, Why does it takes "06/22/2010" as Jan 22? Does anyone face similar problem?

Help me friends.. Thanx in advance..

5条回答
时光不老,我们不散
2楼-- · 2019-02-14 14:25

Month is MM

In your case:

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

查看更多
别忘想泡老子
3楼-- · 2019-02-14 14:33

mm => minutes, not months - you need MM for months - that'll resolve your Jan problem!

查看更多
Fickle 薄情
4楼-- · 2019-02-14 14:40

The other answers correctly solved your specific problem.

LocalDate

But there is a larger solution. If you are starting with only dates, no time-of-day and no time zones, then you should be using the LocalDate class rather than DateTime.

Time Zone

Your code ignores the crucial issue of time zones. Time zones matter even for LocalDate, when trying to determine "today". Do you want today's date in Montréal or in Paris. A new day dawns in Paris earlier. When you omit time zone, you get the JVM’s current default time zone.

Joda-Time Can Parse

Furthermore, let Joda-Time do the parsing. No need to be using java.util.Date & .Calendar at all. Joda-time's formatting characters are almost the same as java.util.Date but not entirely so be sire to consult the doc. In this case it it identical.

DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate past = formatter.parseLocalDate( "06/22/2010" );
DateTimeZone = DateTimeZone.forID( "America/Montreal" ): // match time zone intended for that input string.
int days = Days.daysBetween( past, LocalDate.now( timeZone ) );
查看更多
Emotional °昔
5楼-- · 2019-02-14 14:42

It seems like mm refers to minutes, not months, which is MM. Please check here to see the list of appropriate lettering :)

查看更多
Lonely孤独者°
6楼-- · 2019-02-14 14:42

Your pattern is slightly defective. mm is parsed as minutes in hour, you're looking for MM which is month of year.

查看更多
登录 后发表回答