# test like this: perl this_script.pl '02/04/2003 06:30 PM' use strict; sub prepareFormat { my $format = shift; # TODO: check that only valid characters appear in the format # The logic should be: for any character A-Z in the format string, # die if it's not one of: Y M D h m s p my ($i, @order) = 0; my $num_chars = 'YMDhms'; $format =~ s/([$num_chars]+)(\?)?/ $order[$i++] = substr($1,0,1); '('.('\d' x length($1))."$2)"/ge; # use "p" for AM/PM $format =~ s/pp/ $order[$i++] = substr('p',0,1); "(AM|PM)"/e; $format = qr/^(?:$format)$/; return [$format, \@order]; } sub parseDate { my ($format, $date) = @_; my @data = ($date =~ $format->[0]) or return; my %result; for(my $i = 0; $i <= $#data; $i++) { $result{$format->[1]->[$i]} ||= $data[$i]; } $result{h} += 12 if ($result{p} eq 'PM' and $result{h} != 12); $result{h} = 0 if ($result{p} eq 'AM' and $result{h} == 12); return map $result{$_}, qw(Y M D h m s); } #my $format = prepareFormat ('YYYY/MM/DD'); #my $format = prepareFormat ('YYYY-DD-MM|YYYY-DD-M|YYYY-D-MM|YYYY-D-M'); #my $format = prepareFormat ('YYYY-DD?-MM?'); #my $format = prepareFormat ('YYYY-DD?-MM? hh?:mm?'); #my $format = prepareFormat ('YYYY-DD?-MM? hh?:mm?(?::ss?)?'); #my $format = prepareFormat ('YYYY-DD?-MM?(?: hh?:mm?(?::ss?)?)?'); my $format = prepareFormat ('MM/DD/YYYY hh:mm pp'); my ($year, $month, $day, $hour, $min, $sec) = parseDate($format, $ARGV[0]) or print "\tNot in the right format!\n" and exit; print "Year: $year, Month: $month, Day: $day, Hour: $hour, Min: $min, Sec: $sec\n";