Current Date and Time in Perl


Let's start with localtime() function in Perl, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function while using in list context −

sec, # seconds of minutes from 0 to 61
min, # minutes of hour from 0 to 59
hour, # hours of day from 0 to 24
mday, # day of month from 1 to 31
mon, # month of year from 0 to 11
year, # year since 1900
wday, # days since sunday
yday, # days since January 1st
isdst # hours of daylight savings time

Try the following example to print different elements returned by localtime() function −

Example

 Live Demo

#!/usr/local/bin/perl
@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
print "$mday $months[$mon] $days[$wday]\n";

Output

When the above code is executed, it produces the following result −

16 Feb Sat

If you will use localtime() function in the scalar context, then it will return date and time from the current time zone set in the system. Try the following example to print the current date and time in full format −

Example

 Live Demo

#!/usr/local/bin/perl
$datestring = localtime();
print "Local date and time $datestring\n";

Output

When the above code is executed, it produces the following result −

Local date and time Sat Feb 16 06:50:45 2013

Updated on: 29-Nov-2019

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements