How to get Local and UTC date and time in Perl with code example
Multiple ways to get Unix timestamp in Perl
- using Perl’s Inbuilt time function, which returns a long number.
time()outputs the long number
- time function in cpan
What is the Current Epoch(Unix) time in Perl
Epoch time is the total number of seconds, the ie long number represents that already passed from 1 January 1970 UTC.
the total number of seconds per day is
24\* 60\*60 seconds. Epoch time returns the long number between the current time and
1 January 1970.
It is also called
Epoch Unix time.
Perl language provides API for getting Unix time. There are cpan modules that also provide a Date API for manipulation of Epoch Time.
the base year is 1970 since UNIX OS was introduced at that time.
EPOCH time = unix epoch time = Number of millseconds 01/01/1970 00:00:00
Perl Unix timestamp in milliseconds
Perl provides a native time() function that returns the current epoch Unix time.
my $unixTime = time(); print "$unixTime";
Another way using the
time function in the
use strict; use warnings; use Time::HiRes qw(time); my $unixTime = time(); print "$unixTime";
How to Convert timestamp to Date and time in Perl
First, get timestamp using the time() function next, pass the timestamp to the localtime() 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";
Timestamp: 1671377748.28593 Convert timestamp to date: Sun Dec 18 21:05:48 2022