In Perl, localtime
takes a Unix timestamp and gives back year/month/day/hour/min/sec etc. I'm looking for the opposite of localtime
: I have the parts, and I'd like to build a unix timestamp from them.
views:
2371answers:
4DateTime on CPAN might of of some use. It also has a lot of time manipulation/translation methods.
Just create the DateTime using your parts and call $datetime->formatter("%s") ;
You can use the timelocal funtion in the Time::Local CPAN module.
NAME
Time::Local - efficiently compute time from local and GMT time
SYNOPSIS
$time = timelocal($sec,$min,$hour,$mday,$mon,$year); $time = timegm($sec,$min,$hour,$mday,$mon,$year);
DESCRIPTION
This module provides functions that are the inverse of built-in perl functions localtime() and gmtime(). They accept a date as a six-element array, and return the corresponding time(2) value in seconds since the system epoch (Midnight, January 1, 1970 GMT on Unix, for example). This value can be positive or negative, though POSIX only requires support for positive values, so dates before the system's epoch may not work on all operating systems.
It is worth drawing particular attention to the expected ranges for the values provided. The value for the day of the month is the actual day (ie 1..31), while the month is the number of months since January (0..11). This is consistent with the values returned from localtime() and gmtime().
Note: POSIX::mktime is a just a wrapper around your C library's mktime()
function. Time::Local is a pure-Perl implementation, and always returns results matching Perl's localtime
. Also, Time::Local offers gmtime
, while mktime
only works in local time. (Well, you could try changing $ENV{TZ}
, but that doesn't work on some systems.)
There is, of course, more than one way to do it. Here's another (more OO) angle:
use DateTime;
my $dt = DateTime->new(
year => $year,
month => $month,
day => $day,
hour => $hour,
minute => $minute,
second => $second,
time_zone => 'local',
);
print $dt->epoch(), "\n";