Perl provides several built-in modules and functions for working with dates and times. The most common ones are:
1. ‘localtime‘: This function takes an epoch time (the number of seconds since January 1, 1970, UTC) and returns an array of values representing the corresponding local time.
my $epoch_time = time(); # Get the current epoch time
my ($sec, $min, $hour, $day, $mon, $year) = localtime($epoch_time);
# Print the current date and time
printf("Current date and time: %04d/%02d/%02d %02d:%02d:%02dn",
$year+1900, $mon+1, $day, $hour, $min, $sec);
This will output something like:
Current date and time: 2022/08/11 23:24:09
The ‘localtime‘ function returns an array of values representing the local time in the following order: seconds, minutes, hours, day of the month (1-31), month (0-11), year (since 1900), weekday (0-6, 0 is Sunday), day of the year (0-365), and whether daylight saving time is in effect (0 or 1). Note that the month value starts at 0 for January, so you need to add 1 to get the actual month number (hence the ‘$mon+1‘ in the example).
2. ‘gmtime‘: This function is similar to ‘localtime‘ but returns the corresponding time in Coordinated Universal Time (UTC) instead of the local time.
my $epoch_time = time(); # Get the current epoch time
my ($sec, $min, $hour, $day, $mon, $year) = gmtime($epoch_time);
# Print the current UTC date and time
printf("Current UTC date and time: %04d/%02d/%02d %02d:%02d:%02dn",
$year+1900, $mon+1, $day, $hour, $min, $sec);
This will output something like:
Current UTC date and time: 2022/08/11 17:25:09
3. ‘DateTime‘: This module provides a more powerful and flexible interface for working with dates and times in Perl. It allows for easy creation, manipulation, and formatting of dates and times, as well as support for time zones and various calendar systems.
Here’s an example of using ‘DateTime‘ to get the current local date and time:
use DateTime;
my $dt = DateTime->now; # Get the current local date and time
print("Current date and time: ", $dt->datetime, "n");
This will output something like:
Current date and time: 2022-08-11T23:27:09
‘DateTime->now‘ creates a ‘DateTime‘ object representing the current local date and time. The ‘datetime‘ method returns a string representation of the date and time in ISO 8601 format (‘YYYY-MM-DDTHH:MM:SS‘). ‘DateTime‘ also provides many other useful methods for working with dates and times, such as ‘add‘, ‘subtract‘, ‘compare‘, and ‘format‘.
In summary, Perl provides several built-in modules and functions for working with dates and times, such as ‘localtime‘ and ‘gmtime‘ for getting the current local or UTC date and time, and ‘DateTime‘ for more powerful and flexible manipulation of dates and times.