in reply to checking dates in strings

I don't think it will be easy to have a single regexp to validate dates, if you really want to validate every detail. Also complex regexp seems to me as a bad habit, as it stops people from understanding and maintaining code. Here is my solution, hope it helps you:
use strict; my @last_day = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); sub is_leap_year { my $year = shift; my $result; if ($year % 4) { $result = 0; } else { $result = 1; if (!($result % 100)) { $result = 0; if (!($result % 400)) { $result = 1; } } } return $result; } sub is_validate_date { my $date = shift; $date =~ m/(\d+)-(\d+)-(\d+)/; my $year = $3; my $month = $2; my $day = $1; my $result = 1; if (($month > 12) || ($month < 1)) { $result = 0; } else { if ($day > $last_day[$month - 1]) { $result = 0; } else { if (!is_leap_year($year) && ($month == 2) && ($day > 28)) +{ $result = 0; } } } return $result; } my $date = "29-02-2000"; print is_validate_date($date);

Replies are listed 'Best First'.
Re: Re: checking dates in strings
by FamousLongAgo (Friar) on Nov 11, 2002 at 01:10 UTC
    I would strongly advise you consider using an existing CPAN module, like Date::Manip. That way, you can:

    1. Avoid having to reinvent code that already exists
    2. Avoid getting bitten by the many special cases in date processing
    3. Easily update your program if you find you need to support more than this particular date format


    And if you want to improve your understanding of date handling, looking at the source of existing modules is a good place to start.

      I fully agree with you. There is also another package we can use for this purpose, but less natural than your suggestion:
      use HTTP::Date qw(parse_date); my ($year, $month, $day, $hour, $$minute, $second, $timezone) = parse_ +date("11-12-2002"); print "year = $year\n"; print "month = $month\n"; print "day = $day\n";