This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Date difference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date difference " Watch "Date difference " New topic

Date difference

Vivian Josh
Ranch Hand

Joined: Oct 31, 2006
Posts: 112
Hi Ranchers,

I don't know what I am missing to understand in following code but I was trying to get date difference of following two dates and its giving me 0

Calendar cal = new GregorianCalendar(2008, 10, 31, 10, 00);
Long start = cal.getTimeInMillis();
Calendar cal2 = new GregorianCalendar(2008, 11, 1, 10, 00);
Long end = cal2.getTimeInMillis();

Output :

Start Date in ms = 1228154400000
End Date in ms = 1228154400000
Diff = 0

Start date - 31st oct 10 am
End date - Nov. 1 , 10 am

Shouldn't it give me 24 hrs?

Jeanne Boyarsky
internet detective

Joined: May 26, 2003
Posts: 30130

No. If you run

you see both dates are "Mon Dec 01 10:00:00 EST 2008".

Note that the month is "zero" based. Meaning cal2 is December (month 11).

Cal is "November 31st." Since November only has 30 days, Java rolls it to December 1st for you. Since both dates are the same, you get the zero.

One thing - you can use constants to avoid having to code months that aren't intuitive. For example:
Calendar cal2 = new GregorianCalendar(2008, Calendar.DECEMBER, 1, 10, 00);

[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Consider Paul's rocket mass heater.
subject: Date difference
Similar Threads
Issues with fetching Year and Month from the Calender
Calendar() / Date() bug ???
How to compare time reliably
3 Oct 2010 only has 23 hours?
DateFormat.format unexpected side effect