ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
3.7. Parsing Dates and Times from StringsProblemYou read in a date or time specification in an arbitrary format but need to convert that string into distinct year, month, etc. values. SolutionIf your date is already numeric, or in a rigid and easily parsed format, use a regular expression (and possibly a hash mapping month names to numbers) to extract individual day, month, and year values, and then use the standard Time::Local module's use Time::Local; # $date is "1998-06-03" (YYYY-MM-DD form). ($yyyy, $mm, $dd) = ($date =~ /(\d+)-(\d+)-(\d+)/; # calculate epoch seconds at midnight on that day in this timezone $epoch_seconds = timelocal(0, 0, 0, $dd, $mm, $yyyy); For a more flexible solution, use the use Date::Manip qw(ParseDate UnixDate); $date = ParseDate($STRING); if (!$date) { # bad date } else { @VALUES = UnixDate($date, @FORMATS); } DiscussionThe flexible
use Date::Manip qw(ParseDate UnixDate); while (<>) { $date = ParseDate($_); if (!$date) { warn "Bad date string: $_\n"; next; } else { ($year, $month, $day) = UnixDate($date, "%Y", "%m", "%d"); print "Date was $month/$day/$year\n"; } } See AlsoThe documentation for the CPAN module Date::Manip; we use this in Recipe 3.11 |