How to get started with Linux: the conversion between local time and UNIX timestamp in Perl
Problem: in Perl, I need to convert the readable date and time to the corresponding UNIX timestamp, and vice versa. Can you give me some Perl code examples that convert date and time to UNIX timestamp? Alternatively, convert the UNIX timestamp to the readable date and time.
When your Perl script needs to solve the time information, there are two methods to represent and process the date and time. One method is the easy-to-read time representation (for example, "Sat Mar 14 10:14:05 EDT 2015"), and the other is the UNIX timestamp (also called "New Era time "), this is the number of seconds that have elapsed since January 1, January 1, 1970. Each method has its own advantages and disadvantages. Depending on your needs, you may need to convert one format to another.
Convert local time to UNIX timestamp in Perl
To obtain UNIX time from a Date string, use the str2time () function in the Date: Parse module. This function can process multiple formats, such:
- Sat Mar 14 10:14:05 EDT 2015
- 3/14/2015 10:14:05-0400
- 14/Mar/10:14:05
- 14 Mar 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);
Date: The 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 timestamp in Perl to readable Date and Time
If you want to convert a UNIX timestamp to a readable format, you can use the localtime () function. This function can convert a UNIX timestamp 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:
# $ Sec, $ min, $ hour: seconds, minutes, hours
# $ Mday: The day of the month (0-31)
# $ Mon: Month, ranging from 0 (January 1, January) to 11 (January 1, December)
# $ Year: the year, the difference from January 1, 2015 (January 1, 1900-115 =)
# $ Wday: Week, ranging from 0 (Sunday) to 6 (Saturday)
# $ Yday: one day in a year, ranging from 0 to 364 (or 365 leap year)
# $ Isdst: whether it is timeout
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";
This article permanently updates the link address: