divt
asked on
calculate number of days between 2 dates (without external modules)
Problem illustration:
All inputs in format 'dd/mm/yyyy'
sample input A:
$date1 = '21/10/2004';
$date2 = '25/10/2004';
sample output A:
4
sample input B:
$date1 = '21/10/2004';
$date2 = '21/10/2005';
sample output B:
365
sample input C:
$date1 = '21/10/2004';
$date2 = '21/10/2020';
sample output C:
5844
Without using third party modules (Date::Calc etc.)
Must calculate correctly with leap years, etc.
Does this sound like reinventing the wheel?
Opinions welcome.
All inputs in format 'dd/mm/yyyy'
sample input A:
$date1 = '21/10/2004';
$date2 = '25/10/2004';
sample output A:
4
sample input B:
$date1 = '21/10/2004';
$date2 = '21/10/2005';
sample output B:
365
sample input C:
$date1 = '21/10/2004';
$date2 = '21/10/2020';
sample output C:
5844
Without using third party modules (Date::Calc etc.)
Must calculate correctly with leap years, etc.
Does this sound like reinventing the wheel?
Opinions welcome.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
"timelocal" is defined in Time::Local. It does the reverse of "localtime" in that it constructs a unix timestamp from date parts:
$time = timelocal($sec,$min,$hour, $mday,$mon ,$year);
So timelocal(localtime($time) ) == $time.
$time = timelocal($sec,$min,$hour,
So timelocal(localtime($time)
thx kandura
excellent explanation
excellent explanation
return int($diff / 86400)
Could give the wrong answer if $d1 and $d2 cross a Daylight Saving Time transition.
Could give the wrong answer if $d1 and $d2 cross a Daylight Saving Time transition.
I'll leave that as an excercise for the reader ;)
I'd like to see an example of that, ozo.
daydiff('27/3/2004', '29/3/2004') = 1
(I'm in CET)
ok. better use timegm instead of timelocal.
(I'm in CET)
ok. better use timegm instead of timelocal.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I don't think he was looking for golfed but excellent obfuscated solution. I doubt most people will be able to even follow it but I enjoyed it! :-)
ASKER
Well, you may enjoy it, but I had a hard time digesting answers from you all experts! :-)
All answers yield the correct results for the illustratted problem. Thank you for showing me the flexibility of perl.
By the way, Ozo, what does JDN stand for?
All answers yield the correct results for the illustratted problem. Thank you for showing me the flexibility of perl.
By the way, Ozo, what does JDN stand for?
Julian Day Number
I didnt not get the logic of return timelocal(0,0,0,$d, $m-1, $y);
cud u pls elaborate
thx
ronan