• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Date Difference ??? a Issue...???

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

CODE 1 :
String startDate = "01/01/2004";
String endDate = "02/01/2005";
String st[] = startDate.split("/");
String end[] = endDate.split("/");
String mnth = st[0];String day = st[1];String yr = st[2];
String mnth1 = end[0];String day1 = end[1];String yr1 = end[2];
Calendar scal = Calendar.getInstance();
Calendar ecal = Calendar.getInstance();
scal.set(Integer.valueOf(yr), Integer.valueOf(mnth), Integer.valueOf(day));
ecal.set(Integer.valueOf(yr1), Integer.valueOf(mnth1), Integer.valueOf(day1));
long difInDays = ((ecal.getTime().getTime() - scal.getTime().getTime()) / (1000 * 60 * 60 * 24));

CODE 2 :

Date date1 = new Date(startDate);
Date date2 = new Date(endDate);
long diff = date2.getTime() - date1.getTime();
int days = (int)Math.ceil( diff/86400000 );

The DiffInDays Differs for the CODE 1 and CODE 2...,,
As the difference for the second line should be 397 which is correct in CODE 2
but in CODE 1 it gives a diferent value....!!!

Is this Difference a Issue in Java version...???


StartDate EndDate DiffInDays
CODE 1: 01/01/2004 01/31/2005 396
CODE 2: 01/01/2004 02/01/2005 394


CODE 2: 01/01/2004 01/31/2005 396
CODE 2: 01/01/2004 02/01/2005 397

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, clearly your second example where the Date objects are instantiated directly are producing the result correctly, while your own parsing is not. Try adding some debug statements - print out individual variables you are using and see where the answer first differs from the expected result.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use DateFormat and SimpleDateFormat to convert a String into a Date. It's must more robust than your first piece of code, and in the second piece of code you're using a deprecated Date constructor.
reply
    Bookmark Topic Watch Topic
  • New Topic