Results 1 to 19 of 19
  1. #1
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Default Best way to find number of days between 2 dates??

    Hi All

    After much searching on the internet I have written the below piece of code to find the number of days between 2 dates. Seems to be working accurately but would like your suggestions for improvement.

    Java Code:
    public static long daysBtwTwoDates(Date date1, Date date2) 
    	{
    		// Create temporary calendar objects for the two dates and set the times
    		// to 11:30:00 and time-zones to UTC as we are only concerned with
    		// difference between days.
    		Calendar tmpStartDate = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    		tmpStartDate.setTime(date1);
    		tmpStartDate.set(Calendar.HOUR, 11);
    		tmpStartDate.set(Calendar.MINUTE, 30);
    		tmpStartDate.set(Calendar.SECOND, 0);
    
    		Calendar tmpEndDate = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    		tmpEndDate.setTime(date2);
    		tmpEndDate.set(Calendar.HOUR, 11);
    		tmpEndDate.set(Calendar.MINUTE, 30);
    		tmpEndDate.set(Calendar.SECOND, 0);
    
    		long endDateL = tmpEndDate.getTimeInMillis()
    				+ tmpEndDate.getTimeZone().getOffset( tmpEndDate.getTimeInMillis()) ;
    
    		//add 2000ms = 2s to cover the time taken between extracting 2 long numbers.
    		long startDateL = tmpStartDate.getTimeInMillis()
    				+ tmpStartDate.getTimeZone().getOffset(	tmpStartDate.getTimeInMillis())+2000;
    		
    		long noOfDays = 0;
    		final long MILLIS_IN_DAY = 1000*60*60*24;
    		for( ; startDateL < endDateL; startDateL+=MILLIS_IN_DAY, noOfDays++ );
    		
    		return noOfDays;
    		//return (endDateL - startDateL) / MILLIS_IN_DAY;
    	}

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    A Calendar and a loop adding (and counting) a day at a time (and a month at a time using getActualMaximum and a year at a time also using getActualMaximum).

  3. #3
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Default

    Quote Originally Posted by masijade View Post
    A Calendar and a loop adding (and counting) a day at a time (and a month at a time using getActualMaximum and a year at a time also using getActualMaximum).
    Sorry didnt entirely understand what you are getting at. Can you please post some code ?


    thanks a lot :)

  4. #4
    RockoAndy is offline Member
    Join Date
    Sep 2010
    Posts
    3
    Rep Power
    0

    Default

    Hi its basically same approach you have used but this eliminates the for loop



    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    cal.setTime(new Date());
    System.out.println(cal.getTime());
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(new Date());
    cal1.set(Calendar.DATE,cal1.get(Calendar.DATE)+ 100 );
    System.out.println(cal1.getTime());
    if(cal1.after(cal))
    {
    long difference = cal1.getTimeInMillis()- cal.getTimeInMillis();
    System.out.println(difference);
    long oneDay = 24*60*60*1000;
    System.out.println("No of Days"+difference/oneDay);

    }else
    {
    long difference = cal1.getTimeInMillis()- cal.getTimeInMillis();
    System.out.println(difference);
    long oneDay = 24*60*60*1000;
    System.out.println("No of Days"+difference/oneDay);
    }

  5. #5
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Quote Originally Posted by RockoAndy View Post
    Hi its basically same approach you have used but this eliminates the for loop
    Incorrectly, though. For a "few" days, yeah it works. A general solution it is not.

  6. #6
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Quote Originally Posted by alinaqvi90 View Post
    Sorry didnt entirely understand what you are getting at. Can you please post some code ?


    thanks a lot :)
    Create a calendar using the start date. Create a calendar using the end date. Set the time on both dates to midnight (or noon). Then start looping, adding a day at a time to the "start" date (using the add method) while keeping a count, until the start date = the end date.

    See the API docs for Calendar, of course.

  7. #7
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Smile

    Try using this:

    long mills_per_day = 1000 * 60 * 60 * 24;

    long day_diff = ( secondDate.getTime() - firstDate.getTime() ) / mills_per_day;

    System.out.println(day_diff);

    here, firstDate and secondDate, both are objects of type java.util.Date

  8. #8
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Quote Originally Posted by lovelesh View Post
    Try using this:

    long mills_per_day = 1000 * 60 * 60 * 24;

    long day_diff = ( secondDate.getTime() - firstDate.getTime() ) / mills_per_day;

    System.out.println(day_diff);

    here, firstDate and secondDate, both are objects of type java.util.Date
    And it is still incorrect. For a few days, fine, for a longer time period, no.

  9. #9
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Default

    Quote Originally Posted by masijade View Post
    And it is still incorrect. For a few days, fine, for a longer time period, no.
    Can you please give some sample dates for which it doesn't works?

  10. #10
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    A day is, under general definition, that length of time, but it does not take leap seconds into account. Some days are longer than others.

  11. #11
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Default

    Quote Originally Posted by masijade View Post
    A day is, under general definition, that length of time, but it does not take leap seconds into account. Some days are longer than others.
    And as a thumb rule I would stay away from using division for doing date calculations.

    masijade
    I actually came across the solution you suggested before implementing my one. In my mind the performance hit would be too much in adding days to the calendar object one at a time.

    What do you think?


    cheers

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by masijade View Post
    A day is, under general definition, that length of time, but it does not take leap seconds into account. Some days are longer than others.
    I was under the impression that the POSIX time system ignores leap seconds.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    I was under the impression that the POSIX time system ignores leap seconds.

    kind regards,

    Jos
    I dont know the exact nitty gritty of things but the algo below is dodgy as this was the first one I implemented from an example off the net.


    "
    long mills_per_day = 1000 * 60 * 60 * 24;

    long day_diff = ( secondDate.getTime() - firstDate.getTime() ) / mills_per_day;

    System.out.println(day_diff);
    "


    thx

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by alinaqvi90 View Post
    I dont know the exact nitty gritty of things but the algo below is dodgy as this was the first one I implemented from an example off the net.

    Java Code:
    long mills_per_day = 1000 * 60 * 60 * 24;
    
    long day_diff = ( secondDate.getTime() - firstDate.getTime() ) / mills_per_day;
    
    System.out.println(day_diff);
    In a POSIX time management system your method works fine because every day is as long as another. The only thing you have to take care of is overflow/underflow of the difference of two long values.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  15. #15
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Post

    Quote Originally Posted by masijade View Post
    A day is, under general definition, that length of time, but it does not take leap seconds into account. Some days are longer than others.
    That's correct!
    Some days are longer than others....But this happens to be
    1 second only and that too... once in a year and half (on an average). So going by that calculation means, the calculations could go wrong when the difference between two dates is more than 129600 years. In the calculations, we have not accounted negative leap seconds (which is also a possibility).

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by lovelesh View Post
    That's correct!
    Some days are longer than others....But this happens to be
    1 second only and that too... once in a year and half (on an average). So going by that calculation means, the calculations could go wrong when the difference between two dates is more than 129600 years. In the calculations, we have not accounted negative leap seconds (which is also a possibility).
    Earth's rotation gradually slows down so I don't think negative leap seconds will ever be necessary.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    alinaqvi90 is offline Member
    Join Date
    May 2010
    Posts
    32
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    ....The only thing you have to take care of is overflow/underflow of the difference of two long values.

    Jos
    how?


    many thanks

  18. #18
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Quote Originally Posted by JosAH View Post
    Earth's rotation gradually slows down so I don't think negative leap seconds will ever be necessary.

    According to this data the astronomical day was shorter than the atomic one over June/July this year, but over the whole year there will still be a "win" by the atomic clocks and a positive (or no) leap second. The earth's slow down (about 2ms per century) won't amount to anything either way over our lifetimes. The reason for the lack of negative leap seconds (so far) seems to be that the competition is rigged in favour of the atomic clocks to start with.

    There's a nice seasonal variation to the excess/deficit in the length of the day. Maybe this is due to the west->east winds across the Pacific in our (Southern) winter hitting the Andes/Rockies.

  19. #19
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,773
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by pbrockway2 View Post
    According to this data the astronomical day was shorter than the atomic one over June/July this year, but over the whole year there will still be a "win" by the atomic clocks and a positive (or no) leap second. The earth's slow down (about 2ms per century) won't amount to anything either way over our lifetimes. The reason for the lack of negative leap seconds (so far) seems to be that the competition is rigged in favour of the atomic clocks to start with.

    There's a nice seasonal variation to the excess/deficit in the length of the day. Maybe this is due to the west->east winds across the Pacific in our (Southern) winter hitting the Andes/Rockies.
    Fascinating isn't it? Earth is just a bit elastic blob in space and everything inside it and above its surface influence the way it rotates; there's nothing solid and stable about it, it's just a blob of moving mud ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Find max number in 2D array?
    By spatel14 in forum New To Java
    Replies: 3
    Last Post: 06-30-2010, 05:27 PM
  2. Find the time between two dates
    By white feather in forum New To Java
    Replies: 1
    Last Post: 04-14-2010, 02:40 PM
  3. Find a number from a string
    By florentp in forum New To Java
    Replies: 2
    Last Post: 03-20-2009, 10:01 PM
  4. Find nth root of a number
    By perito in forum New To Java
    Replies: 1
    Last Post: 03-03-2008, 07:51 AM
  5. No fo days between two dates
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-28-2008, 10:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •