• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Date difference

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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();
System.out.println(start);
Calendar cal2 = new GregorianCalendar(2008, 11, 1, 10, 00);
Long end = cal2.getTimeInMillis();
System.out.println(end);


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?

 
author & internet detective
Posts: 42055
926
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vivian,
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);
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic