Wednesday, August 12, 2009

Translating The Name of Month To Number

Another Perl code posted since I am getting tired of rewriting it all the time.
my %months = (
Jan=>1, Feb=>2, Mar=>3, Apr=>4, May=>5, Jun=>6,
Jul=>7, Aug=>8, Sep=>9, Oct=>10, Nov=>11, Dec=>12,
January=>1, February=>2, March=>3,
April=>4, May=>5, June=>6,
July=>7, August=>8, September=>9,
October=>10, November=>11, December=>12,
);
eg:
parseDate('Jan  1 2009 12:00:00:000AM');

sub parseSQLDate {
my ($txt) = @_;

if ($txt =~ /^(\w+)\s+(\d+)\s+(\d+)\s+(\d+):(\d+):(\d+):(\d+)/) {
use DateTime;

my %months = (
Jan=>1, Feb=>2, Mar=>3, Apr=>4, May=>5, Jun=>6,
Jul=>7, Aug=>8, Sep=>9, Oct=>10, Nov=>11, Dec=>12,
January=>1, February=>2, March=>3,
April=>4, May=>5, June=>6,
July=>7, August=>8, September=>9,
October=>10, November=>11, December=>12,
);

my $dt = DateTime->new(
year => $3,
month => $months{$1},
day => $2,
time_zone => 'floating',
);

return $dt;
}
}

No comments: