***** infoCopter.com/perl *****

Date & Time in Perl

Code snippets about date and time
Scan CPAN for date and time


[ Calculate Time Difference ] - [ www.just-just-just-dating.com/date_perl_time.html ]

my ($y, $m, $d) = (localtime)[5,4,3];

$y += 1900;
$m += 1;

print "$y, $m, $d\n";

Output would be: 2002, 1, 21


my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

my $month = $mon + 1;
my $YYYY  = $year + 1900;

my $d = (localtime)[3];
my $y = (localtime)[5] + 1900;
my $m = (localtime)[4]; 

print localtime(); # amount of seconds since 1970, e.g. 573711711024370

time()

Returns the number of non-leap seconds since whatever time the system considers to be the epoch (that's 00:00:00, January 1, 1904 for MacOS, and 00:00:00 UTC, January 1, 1970 for most other systems). Suitable for feeding to gmtime and localtime.


Access, Modification, Creation Times of a File

my ($atime, $mtime, $ctime) = (stat($ARGV[0]))[8..10];

printf qq~
        Accessed: %s
        Modified: %s
        Created: %s
~,
        get_real_time($atime),
        get_real_time($mtime),
        get_real_time($ctime);

sub get_real_time ($) {
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime $_[0];
        $year += 1900;
        return "$year\-$mday\-$mday $hour:$min:$sec";
}

Tips

The day of the year is in the array returned by localtime() (see the localtime entry in the perlfunc manpage):


$day_of_year = (localtime(time()))[7];

or more legibly (in 5.004 or higher):

use Time::localtime;
$day_of_year = localtime(time())->yday;

You can find the week of the year by dividing this by 7:


$week_of_year = int($day_of_year / 7);

Converting Epoch Seconds to Human Readable String

#!/usr/bin/perl -w
use strict;

use Date::Manip;

my $epoch = $ARGV[0] || time() - 3600 * 24; # yesterday

print "-> epoch = $epoch\n";

my $date = &ParseDateString("epoch $epoch");

print "<- $date\n";
© reto :)