Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes about subtract dates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "about subtract dates" Watch "about subtract dates" New topic
Author

about subtract dates

mohamed abdo
Greenhorn

Joined: Aug 13, 2009
Posts: 8
how can i subtract two dates from each other,i need the result with the days count between them , (date - date = xxx day)
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Moving to a more suitable forum.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10167
    
    8

Check out Calendar#DAY_OF_YEAR and Calendar#get()
mohamed abdo
Greenhorn

Joined: Aug 13, 2009
Posts: 8
thank you sir , i found it
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

That's the naive approach, which is broken because of daylight savings - there are two days a year that are not 24 hours.

The right approach indeed uses Calendar.get() in combination with both Calendar.DAY_OF_YEAR and Calendar.YEAR. In short:
- subtract the day of year of the first date from the day of year of the second date
- add the number of days for each year in difference as well; use Calendar.getActualMaximum(Calendar.DAY_OF_YEAR) to determine how many days a year has.

To make it easier, you can swap the operands if the first date is larger than the second:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: about subtract dates
 
Similar Threads
Parsing dates
Difference beteween two dates
Can anyone recommend good date utlities...
Date difference, with the table containing null values for date
DateDiff Function in Java?