Re: How to convert timestamp to epoch?
- From: "jl_post@xxxxxxxxxxx" <jl_post@xxxxxxxxxxx>
- Date: Tue, 30 Oct 2007 13:16:41 -0700
On Oct 30, 1:27 pm, TonyV <kingskip...@xxxxxxxxx> wrote:
use Time::Local;
my $ts_to_convert = '22-jun-07 06.16.44.160000 PM';
print timestamp_to_epoch($ts_to_convert);
sub timestamp_to_epoch {
my ($ts) = @_;
my %month = (
'JAN' => 0, 'FEB' => 1, 'MAR' => 2, 'APR' => 3,
'MAY' => 4, 'JUN' => 5, 'JUL' => 6, 'AUG' => 7,
'SEP' => 8, 'OCT' => 9, 'NOV' => 10, 'DEC' => 11);
my $regex = '^(\d{1,2})-(\w{1,3})-(\d{1,2}) ';
$regex .= '(\d{1,2})\.(\d{1,2})\.(\d{1,2})';
$regex .= '\.\d+ ([AP])M$';
if ($ts =~ m{$regex}i) {
my ($dd, $mo, $yy, $hh, $mm, $ss, $ap) =
($1, $2, $3, $4, $5, $6, $7);
$yy += 2000; $mo = $month{uc($mo)};
$hh += 12 if (uc($ap) eq 'P');
return timelocal($ss, $mm, $hh, $dd, $mo, $yy);
}
else { return 0; }
}
Ummm... this code has a subtle error in it: it won't correctly
convert dates with "12" as the hour. To see what I mean, try running
your code with this line:
my $ts_to_convert = '22-JUN-07 12.16.44.160000 PM';
Instead of an epoch time value, you'll see an error message like:
Hour '24' out of range 0..23
Converting 12-hour AM/PM time to 24-hour time (and vice-versa) is a
little trickier than many people think. They often forget to check
the cases where the hour equals 12, thinking that simply adding 12 to
the hour (if they are in PM) is enough to convert from 12-hour to 24-
hour time (like in the code you gave).
But "12:00 am" needs to be converted to "00:00" and "12:00 pm"
needs to be converted to "12:00", and just adding 12 to the hour value
won't correctly convert either.
.
- References:
- How to convert timestamp to epoch?
- From: void.no.spam.com@xxxxxxxxx
- Re: How to convert timestamp to epoch?
- From: TonyV
- Re: How to convert timestamp to epoch?
- From: TonyV
- How to convert timestamp to epoch?
- Prev by Date: Re: Regular Expression and Useage
- Next by Date: Re: Regular Expression and Useage
- Previous by thread: Re: How to convert timestamp to epoch?
- Next by thread: Re: How to convert timestamp to epoch?
- Index(es):