perl function localtime

www‮‬.theitroad.com

In Perl, the localtime function is used to convert a UNIX timestamp (the number of seconds since January 1, 1970, GMT) into a list of time values that are appropriate for the local time zone. The values returned by localtime can be used to display the date and time in a human-readable format.

Here's an example that demonstrates how to use localtime:

#!/usr/bin/perl

use strict;
use warnings;

# Get the current UNIX timestamp
my $timestamp = time();

# Convert the timestamp to local time
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($timestamp);

# Print the local date and time
printf "Local time: %04d-%02d-%02d %02d:%02d:%02d\n", $year + 1900, $mon + 1, $mday, $hour, $min, $sec;

In this example, we use the time function to get the current UNIX timestamp. We then pass this timestamp to the localtime function, which returns a list of time values that are appropriate for the local time zone.

We use the list of time values to display the local date and time in a human-readable format using printf. The format string "%04d-%02d-%02d %02d:%02d:%02d" specifies the desired format for the date and time. The values $year + 1900, $mon + 1, $mday, $hour, $min, and $sec are substituted into the format string to generate the final output.

When we run this script, it will output something like the following:

Local time: 2023-03-03 14:27:16

As we can see, the localtime function has converted the UNIX timestamp to the local date and time in a human-readable format.