Problem with Comparing Dates (urgent!)
Hi,
I have a script which is supposed to compare 2 dates. If $date1 le $date2, then it's supposed to do something. But I just realised that when it compares, because they're both strings, it only compares by the first digit. So to me, 06 November 2001 is greater than 25 October 2001, but to perl, it's less than. How do I fix this so that it compares not the first digit, but the actual calendar date?
I would desperately love some help on this one...
Thanks
Mark Hensler posted this at 05:20 — 24th October 2001.
He has: 4,048 posts
Joined: Aug 2000
You need to compair numbers.
Assuming the format "day month year", try this:
#!/usr/bin/perl
sub Numberfy_Date($string_date) {
$pieces = split(/ /,$string_date);
$day = $pieces[0];
$year = $pieces[2]
if ($pieces[1] == "January") $month = "01";
if ($pieces[1] == "February") $month = "02";
if ($pieces[1] == "March") $month = "03";
if ($pieces[1] == "April") $month = "04";
if ($pieces[1] == "May") $month = "05";
if ($pieces[1] == "June") $month = "06";
if ($pieces[1] == "July") $month = "07";
if ($pieces[1] == "August") $month = "08";
if ($pieces[1] == "September") $month = "09";
if ($pieces[1] == "October") $month = "10";
if ($pieces[1] == "November") $month = "11";
if ($pieces[1] == "December") $month = "12";
return ($year . $month . $day);
}
$date1 = "06 November 2001";
$date2 = "25 October 2001";
if (&Numberfy_Date($date1) le &Numberfy_Date($date2)) {
# do something
}
Mark Hensler
If there is no answer on Google, then there is no question.
rline posted this at 06:58 — 24th October 2001.
They have: 40 posts
Joined: Oct 2001
Thanks a lot Mark,
Not sure why, but me and subroutines don't go...I just spent the best part of an hour trying to debug the thing. As soon as I took it out of the subroutine, it worked. So at least now it behaves as I want it.
Thanks again for your quick response!
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.