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 10:14:05 EDT 2015 3/14/2015 10:14:05-0400 14/mar/15 10:14:05 (Mar) 10:14:05 use
Date::P ars e;
My $local _time = "Sat Mar 10:14:05 EDT 2015";
# 1426342445 'll be stored into $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:
Use Date::P arse;
Use Date::language;
My $lang = date::language->new (' French ');
My $unix _time = $lang->str2time ("12:14:05, Ago, 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, time
# $mday: One day of the month (0-31)
# $mon: Month, range 0 (January) to 11 (December)
# $year: Year, and 1900 difference (2015 is 2 015-1900=115)
# $wday: Week, range 0 (Sunday) to 6 (Saturday)
# $yday: One day of the year, range 0 to 364 (or 365 leap year)
# $isdst: 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";