• Post Reply Bookmark Topic Watch Topic
  • New Topic

Date Computation  RSS feed

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Scott Selikoff
author
Bartender
Posts: 4093
21
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jan Groth
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!