0

I am trying to write function to find day difference between two date it work ok but the result change some time in the same inputs .Let say the current date is 21/7/2014 the result some time is 567 and other time 566.

The code:

    //TO GET THE CURRENT DATE
    Calendar cal = Calendar.getInstance();
    //THE CAL.ADD BECUSE THE 1ST MONTH IN THE YEAR IS 0 NOT 1
    cal.add(Calendar.MONTH, 1);

    //TO SET THE START DATE WICH IS 1/1/2013
    Calendar startDate=Calendar.getInstance();
    startDate.set(Calendar.DAY_OF_MONTH, 1);
    startDate.set(Calendar.MONTH,1);
    startDate.set(Calendar.YEAR, 2013);

    //TO FIND THE DIFF BETWEEN THE START DATE AND CUREENT DATE , THE +1 BECUSE IT IS           
    ALWAYS LESS BY ONE DAY
    long diff=(((cal.getTimeInMillis()- 
    startDate.getTimeInMillis())/(1000*60*60*24))+1);
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances They determined that using Joda Time is the best way to handle this. However, this solution is quite good in lieu of using the Joda Time library: http://stackoverflow.com/a/10650881/1778273 – Marco Pietro Cirillo Jul 21 '14 at 13:50

2 Answers2

0

I think this is because of the hours which get rounded in a strange way..

On my side when I add the following code it seems to work fine:

cal.set(Calendar.HOUR_OF_DAY, 1);
startDate.set(Calendar.HOUR_OF_DAY, 1);
Arkillon
  • 51
  • 4
0

The problem here is when you are instantiating a calendar, you are getting current date and time. So when you ignore time values it works perfectly.

Two compare two dates it's better to use Date class and java and use the following code So your above code can be rewritten as

Date cal = new Date(114, 7, 21); //Date is 21/7/2014
Date startDate = new Date(113, 1, 1); Date is 1/1/2013 
long newdiff = ((cal.getTime()-startDate.getTime())/(1000*60*60*24));
System.out.println(newdiff);

This time it will print 566 correctly (The actuall difference is 566)

The problem really is that suppose you are comparing today's date and tomorrow'date.

ie 21/7/2014 and 22/7/2014. The difference in days is one. If you run the program at 12:00 am midnight you will get 1. and at any other time after that it will result in 0. This is because of getting current time along with the date

capt.swag
  • 10,335
  • 2
  • 41
  • 41
  • Thinks,i try it but i get error "the constructor Date(int,int,int) is deprecated – user3849607 Jul 21 '14 at 14:40
  • Actually that is just a warning showing that the code is old.. Calendar class came to replace date but for your purpose it is better to use date class as it is much more simpler and ease of use – capt.swag Jul 21 '14 at 14:41
  • Thinks your hits was useful,I used GregorianCalendar and it work OK now ,Thinks for your time – user3849607 Jul 21 '14 at 14:54