File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Date Computation Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Date Computation" Watch "Date Computation" New topic
Author

Date Computation

Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 746
Hi, I know this is very basic in Java. But if you guys don't mind I would like to add how to compute the difference of two given dates(For getting the age).

In PHP, you can just specify (aDate - today). I'm just a little curious if you could just subtract 2 Date objects directly and have the same effect? Or am I just hallucinating? Thanks!


SCJP 1.5
http://devpinoy.org/blogs/lamia/ - http://everypesocounts.com/
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3666
    
    2

Depends how precise you want the measurements. My favorite way in finding the difference between two dates is to convert them to long values (milliseconds since the epoch) then subtract them such as:


Take a look at http://javaalmanac.com/egs/java.util/CompDates.html for more examples.


My Blog: Down Home Country Coding with Scott Selikoff
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Depending on what you mean by "difference between dates" you have to be careful. For example, if you start with the difference in two dates long timestamps, you may be missing the distinction between two longs timestamps that occur 10 hours apart on the same day and two long timestamps that occur 10 hours apart on consecutive days. And I haven't even mentioned dealing with leap years!

To find durations in days, I start with two calendar objects (in the same time zone!) and roll them both back to midnight, then extract long time stamps and go from there. To calculate age in years, I extract the year, month and day from the calendar objects and take it from there.

If you work with dates you may want to check out joda time.


There is no emoticon for what I am feeling!
Jan Groth
Ranch Hand

Joined: Feb 03, 2004
Posts: 456
i just developed some financial methods where the date differences were really important. after playing around (and freaking out) with java standard packages, i tried joda time, and solved my problem within minutes...

good luck,
jan
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Date Computation
 
Similar Threads
how can i get the date on next sunday
conversion from Date ojbect to Date object
how to find monday in a selected date
Dates as String
Passed SCEA/OCMJEA