Talk about the method of mutual conversion between local time and UNIX timestamp in Perl

Time:2021-11-30

When your Perl script needs to solve time information, there are two ways to represent and process date and time. One method is an easy to read time representation (for example, “sat Mar 14 10:14:05 EDT 2015”), and the other is to use the UNIX timestamp (also known as “new era time”), which is the number of seconds elapsed from January 1, 1970 to today. Each method has its own advantages and disadvantages. Depending on your needs, you may need to convert one format to another.
Converting local time to UNIX timestamp in Perl

To get the UNIX time from the date string, you can use the str2time() function in the date:: parse module. This function can handle a variety of formats, such as:

?
1
2
3
4
5
6
7
8
9
Sat Mar 14 10:14:05 EDT 2015
3/14/2015 10:14:05 -0400
14/Mar/15 10:14:05
14 Mar 15 10:14:05
 
use Date::Parse;
my $local_time = "Sat Mar 14 10:14:05 EDT 2015";
# 1426342445 will be stored in $unix_time
my $unix_time = str2time($local_time);

Date: the parse module supports multiple languages (English, French, German and Italian) and time zones. For example:

?
1
2
3
4
use Date::Parse;
use Date::Language;
my $lang = Date::Language->new('French');
my $unix_time = $lang->str2time("12:14:05, Ago 16, 2014 (CEST)");

UNIX timestamp in Perl to readable date and time

If you want to convert UNIX timestamps to a readable format, you can use the Localtime () function, which can convert UNIX timestamps to a list of 9 elements. Then you can use the returned list to construct any readable format you need. Here is a code snippet:

?
1
2
3
4
5
6
7
8
9
10
11
12
#$sec, $min, $hour: seconds, minutes, hours
#$mday: day of the month (0-31)
#$mon: month, range 0 (January) to 11 (December)
#$year: year, difference from 1900 (2015-1900 = 115 in 2015)
#$WDAY: week, range 0 (Sunday) to 6 (Saturday)
#$yday: day of the year, range 0 to 364 (or 365 leap years)
#$isdst: is it daylight saving time
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($unix_timestamp);
# necessary conversion of $mon and $year
$mon += 1;
$year += 1900;
print "Current time: $year-$mon-$mday $hour:$min:$sec\n";