This article mainly introduces the method of converting the local time in Perl to the Unix timestamp, mainly using date in Perl::P arse Module, the friends you need can refer to the
When your Perl script needs to resolve time information, here are two ways to represent and process dates and times. One method is an easy to read time representation (for example, "Sat 10:14:05 EDT 2015"), and the other is to use the Unix timestamp (also called "New Age Time"), which is the number of seconds elapsed since January 1, 1970. Each method has its own advantages and disadvantages, depending on your needs, perhaps also need to convert one format to another.
Convert local time to UNIX timestamp in Perl
To obtain a Unix time from a date string, you can use the date::P the Str2time () function in the Arse module. This function can handle several formats, such as:
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
useDate::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);
The Date:parse module supports multiple languages (English, French, German, and Italian) and time zones. For example:
useDate::Parse;
useDate::Language;
my$lang= Date::Language->new('French');
my$unix_time=$lang->str2time("12:14:05, Ago 16, 2014 (CEST)");
Unix time stamp to easy to read date and time in Perl
If you want to convert a Unix timestamp to a readable format, you can use the localtime () function, which converts a Unix timestamp to a list of 9 elements. You can then use the returned list to construct any of the readable formats you need. Here's a snippet of code:
# $ sec, $ min, $ hour: seconds, minutes, hours
# $ mday: day of the month (0-31)
# $ mon: month, range 0 (January) to 11 (December)
# $ year: year, the difference from 1900 (2015-1900 = 115)
# $ wday: week, range 0 (Sunday) to 6 (Saturday)
# $ yday: day of the year, range 0 to 364 (or 365 leap years)
# $ isdst: whether it is 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";