Improved in that it's 4 less lines of code :)
GregorianCalendar date1 = new GregorianCalendar(2008, 01, 15, 0, 0);
GregorianCalendar date2 = new GregorianCalendar(2008, 01, 21, 23, 59);
long diff = Math.abs(date2.getTimeInMillis() - date1.getTimeInMillis());
diff = diff / (1000 * 60 * 60 * 24);
System.out.println(diff);
[Standard code sample disclaimer goes here.]
Don Yantzi
Technical Lead
WebSphere Development Studio Client for iSeries
IBM Toronto Lab
Don Yantzi/Toronto/IBM
01/27/2008 01:57 PM
To
Java Programming on and around the iSeries / AS400
<java400-l@xxxxxxxxxxxx>
cc
Subject
Re: Duration Calculation
Hi Jon,
I was quite surprised to find out Java doesn't have a simple method for
calculating this (we don't do much date manipulation in the RSE). The Java
classes all store time as the number of milliseconds since EPOCH. I guess
this makes it easier to handle timezones and DST stuff. So one way to do
this would be to:
GregorianCalendar date2 = new GregorianCalendar(2000, 01, 15);
GregorianCalendar date1 = new GregorianCalendar(2008, 02, 21);
long diff;
if (date1.before(date2))
diff = date2.getTimeInMillis() - date1.getTimeInMillis();
else
diff = date1.getTimeInMillis() - date2.getTimeInMillis();
diff = diff / (1000 * 60 * 60 * 24); // convert from diff in milliseconds
to days
System.out.println(diff)
There might be a better way. And you might want to test this bit of code
before using it in product [standard IBM code sample disclaimer goes
here].
Don Yantzi
Technical Lead
WebSphere Development Studio Client for iSeries
IBM Toronto Lab
Jon Paris <Jon.Paris@xxxxxxxxxxxxxx>
Sent by: java400-l-bounces@xxxxxxxxxxxx
01/27/2008 01:44 PM
Please respond to
Java Programming on and around the iSeries / AS400
<java400-l@xxxxxxxxxxxx>
To
java400-l@xxxxxxxxxxxx
cc
Subject
Re: Duration Calculation
On 27-Jan-08, at 1:00 PM, java400-l-request@xxxxxxxxxxxx wrote:
You can load it into a java.util.Date, extract the corresponding
number
of milliseconds since 1970.01.01, and you can then take the difference
and round down to number of days.
This is part of the current problem - the date related classes seem
to be trying to deal with Daylight Savings Time or something and when
your dates cross the changeover point the results are inaccurate.
Besides - doesn't it strike you as thoroughly silly that one should
even have to contemplate "playing" with milliseconds to get a count
of a number of days! It is insane that such steps should be required
in a so-called "modern" language.
Buying a package to solve a basic language deficiency just sticks in
my craw I'm afraid.
Jon Paris
www.Partner400.com
www.SystemiDeveloper.com
As an Amazon Associate we earn from qualifying purchases.