Converting DMYHMS to Epoch Seconds
Problem
You want to convert a date, a time, or both with distinct values for day, month, year, etc. to Epoch seconds.
Solution
Use the timelocal
or timegm functions in the standard Time::Local
module, depending on whether the date and time is in the current time
zone or in UTC.
use Time::Local; $TIME = timelocal($sec, $min, $hours, $mday, $mon, $year); $TIME = timegm($sec, $min, $hours, $mday, $mon, $year);
Discussion
The built-in function localtime converts an Epoch
seconds value to distinct DMYHMS values; the
timelocal subroutine from the standard Time::Local
module converts distinct DMYHMS values to an Epoch seconds value.
Here’s an example that shows how to find Epoch seconds for a
time in the current day. It gets the day, month, and year values from
localtime:
# $hours, $minutes, and $seconds represent a time today, # in the current time zone use Time::Local; $time = timelocal($seconds, $minutes, $hours, (localtime)[3,4,5]);
If you’re passing month and year values to
timelocal, it expects values with the same range
as those which localtime returns. Namely, months
start at 0, and years have 1900 subtracted from them.
The timelocal function assumes the
DMYHMS values represent a time in the current
time zone. Time::Local also exports a timegm subroutine that assumes the DMYHMS values represent a time in the GMT time zone. Unfortunately, there is no convenient way to convert from a time zone other than the current local time zone or GMT. The best ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access