Last updated on November 11th, 2024 at 11:31 am
One effective way to show the server’s date and time in Perl is by using the functions sprintf and localtime. While there are several ways to retrieve the date, I am choosing the simplest method to get the current date with Perl.
We are also using strftime and extracting the Hour:Minute:Second as shown below.
#!/usr/bin/perl
use POSIX qw(strftime);
# Get day, month, and year from the localtime function
($day, $month, $year) = (localtime)[3,4,5];
# Format the date to YYYY-MM-DD
$my_date = sprintf("%04d-%02d-%02d\n", $year+1900, $month+1, $day);
# Print the formatted date
print "Todays date is $my_date";
# Get the current time in HH:MM:SS format
my $get_time = strftime "%H:%M:%S", localtime;
# Print the formatted time
print "Time is $get_time\n";
Explanation:
use POSIX qw(strftime);: Imports thestrftimefunction from the POSIX module to format date and time.(localtime)[3,4,5];: Extracts the day, month, and year values from the current local time.sprintf("%04d-%02d-%02d\n", $year+1900, $month+1, $day);: Formats the date toYYYY-MM-DD, adjusting the year by adding 1900 and month by adding 1, sincelocaltimereturns the year as years since 1900 and months as zero-indexed.strftime "%H:%M:%S", localtime;: Retrieves the current time inHH:MM:SSformat.
Sample Output
$ ./today.pl
Todays date is 2022-02-18
Time is 03:09:21