Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the opposite of the localtime function in Perl?

Tags:

timestamp

perl

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.

like image 943
Kip Avatar asked Mar 02 '09 19:03

Kip


2 Answers

You can use the timelocal function 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.)

like image 161
Robert S. Barnes Avatar answered Oct 11 '22 15:10

Robert S. Barnes


POSIX::mktime

like image 37
Liudvikas Bukys Avatar answered Oct 11 '22 15:10

Liudvikas Bukys