How to get Local and UTC date and time in Perl with code example
There are various approaches to retrieve the Unix timestamp in Perl:
- Utilizing Perl’s built-in time function, which returns a long number representing the current time.
- Utilizing the
Time::HiRes
module available on CPAN.
Understanding Epoch (Unix) Time in Perl
Epoch
time denotes the total number of seconds that have elapsed since 1 January 1970 UTC
. This long number signifies the time that has passed from that reference point. Essentially, it’s the count of seconds between the current time and 1 January 1970
.
It is also called Epoch Unix time
.
Perl provides APIs for accessing Unix time. Additionally, CPAN modules offer Date APIs for managing Epoch Time. The concept originates from the introduction of UNIX OS in 1970, hence the base year is 1970.
EPOCH time = Unix epoch time = Number of milliseconds since 01/01/1970 00:00:00.
Perl Unix Timestamp in milliseconds
Using Perl’s Native time() Function
Perl natively supports the
time()
function to retrieve the current Unix timestamp.my $unixTime = time(); print "$unixTime";
Output:
1671371398
Using the Time::HiRes Module
Alternatively, you can utilize the time function within the
Time::HiRes
module for higher precision timestamps.use strict; use warnings; use Time::HiRes qw(time); my $unixTime = time(); print "$unixTime";
1671371399.287
Converting Unix Timestamp to Date and Time in Perl
To convert a timestamp to human-readable date and time.
- Obtain the timestamp using the
time()
function. Pass the timestamp to thelocaltime()
function, which returns the datetime object.
Here is an example
use strict;
use warnings;
use Time::HiRes qw(time);
my $unixTime = time();
print "Timestamp: $unixTime\n";
my $date = localtime($unixTime );
print "Convert timestamp to date: $date";
Output:
Timestamp: 1671377748.28593
Convert timestamp to date: Sun Dec 18 21:05:48 2022
These methods offer flexibility in managing Unix timestamps within Perl scripts.