lisaw has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm looking for a solution to a file timestamp problem that I'm dealing with. I have written a perl-script that will give you the contents of a given directory. I have added a timestamp next to each of the listed files. The problem is, when the date is the 10th of the month, or the 10th month of the year, the timestamp shows as '9' instead of 10. Here's what I'm working with:
foreach $line (sort @files) { $temp_file = "$query/$line"; ($filesize, $filedate, $perm) = (stat($temp_file))[7, 9, 2]; $perm = sprintf "%lo", ($perm & 07777); &getdate; ($a, $b) = split(/\./, $line); if ($b ne "") { print <<"__END_OF_HTML_CODE__"; $filetime $filedate __END_OF_HTML_CODE__ }} sub getdate { ($min, $hr, $day, $mon, $yr) = (localtime($filedate))[1,2,3,4,5]; if ($min < 10) { $min = "0$min"; } if ($hr < 10) { $hr = "0$hr"; } if ($day < 10) { $day = "0$day"; } if ($mon < 10) { $mon = "0$mon"; } $yr = $yr+1900; $filedate = "$mon-$day-$yr"; $filetime = "$hr:$min:00"; }
Thank you for any help that you can provide. lis

Replies are listed 'Best First'.
Re: File Timestamp Question
by Roger (Parson) on Oct 14, 2003 at 00:25 UTC
    This is because the localtime function returns 0-based month. ie., 10th month is returned as 9. 1st month is returned as 0, and so on. To fix this, you just have to add 1 to the month.

    And another observation is that you are not using sprintf to format your date, which makes it a bit messy.

    Have a look at the following simpler version of get date, which uses sprintf to format number with leading 0.

    sub Today() { my ($day, $month, $year) = (localtime)[3,4,5]; return sprintf "%04d%02d%02d", $year + 1900, $month+1, $day; }
    Your code can be rewritten as
    sub getdate { my ($min, $hr, $day, $mon, $yr) = (localtime($filedate))[1,2,3,4,5]; $filedate = sprintf "%02d-%02d-%04d", $mon+1, $day, $yr+1900; $filetime = sprintf "%02d:%02d:00", $hr, $min; }
    cheers. Roger
      see also POSIX::strftime
      This is what I had thought too. But I noticed that it was also showing a '9' on the 10th "day" of each month. Before and after day "10" everything was showing the date fine.
        Are you sure? I tried it on my unix box and it worked perfectly.
        -rwxrwxr-x 1 rlee dev 4140 Oct 10 12:29 links.txt
        prints out
        12:29:00 10-10-2003
Re: File Timestamp Question
by bradcathey (Prior) on Oct 14, 2003 at 01:13 UTC
    Don't forget that the month returned by localtime is zero-based. You need to add 1 to it.