Perl (Scripting) - Date and time using localtime

by
Jeremy Canfield |
Updated: February 22 2022
| Perl (Scripting) articles
The localtime function can be used to return a formatted date time. Here is a basic example of how to use localtime.
#!/usr/bin/perl
use strict;
use warnings;
my $datetime = localtime;
print "$datetime \n";
Running this script should return something like this.
Tue Nov 23 23:51:34 2021
Dumper and Time::Piece can be used to visualize the localtime object.
use Data::Dumper;
use Time::Piece;
print Dumper $datetime;
Which should return something like this.
$VAR1 = bless( [
34, # seconds
51, # minutes
23, # hour
23, # day of the month
10, # month where 0 is January and 11 is December
'121', # year
2, # day of the week
326, # day of the year
0, # 0 means daylight savings is in effect, 1 means not in effect
1637733094, # number of seconds that have elapsed since 12/31/1969
1
], 'Time::Piece' );
Let say you only want to print the current month or year. This can be accomplished by including the POSIX module with strftime.
#!/usr/bin/perl
use POSIX qw(strftime);
use strict;
use warnings;
my $year = strftime "%Y", localtime;
print "$year \n";
Did you find this article helpful?
If so, consider buying me a coffee over at