Perl Examples:

   Date and Time

Perl examples of date and time functions, including conversion to a log date


You can download (or just cut and paste) this code to a file on your computer and then run it.  If you compare the code to the results, it might help explain Perl basics.


Perl Code Disclaimer                                                                         Download this Code

#******** Date/time functions ***********

use strict;

print "\nThe command \"time()\" returns
the current time in Epoch seconds: ";
print time(), "\n";

print "\nthe time is: $hour $min $sec";

#for the reverse, use Time::Local
# $time = timelocal($sec,$min,$hour,
#         $mday,$mon,$year);

print "
Time can also be referenced by an array:
0 = sc
1 = min
2 = hour (military)
3 = day of month
4 = month (0 .. 11) January = 0!
5 = year (from 1900 - don't do a y2k thing)
6 = day of week (0 to 6, 0 = Sunday)
7 = day of year
8 = is DST  (1/0 true/false)

my(@list, $x);
# loop through all list items
for $x (0..$#list) {
    print "$x = $list[$x], ";
    } # end of loop

print "
the output of localtime is dependent
on what it is assigned to if it is to a
scalar it will be a formatted time string

print "\nThe local time is: $x\n";

@months = ("January","February","March",

# or without having to specify quotes
@months = qw(January February March April
             May June July August
             September October November

# how to show the current date?
$wday,$yday,$isdst) = localtime(time);

# use the above array to get month name
print "Month is: ".$months[$mon]."  \n\n";

# convert to numeric yyyy-mm-dd date
# month starts at zero so add 1

# fill in leading 0s
$mon    = sprintf("%02u", $mon);
$mday   = sprintf("%02u", $mday);
$year+=1900;      # don't do a y2k thing

print "Date in numeric form:\n";
print "$year-$mon-$mday";

Feel like leaving

A comment?

Use the associated Blog