Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 155
  • Last Modified:

A question about files and dates!

I am currently writing a Perl CGI Script that will display the date of the files that have been uploaded to our website.  Basically I want it to display the date in dd-mmm-yyyy format (eg 25-Jan-1999).  

How can I write a piece of perl code that will get the date of a given file and then display the date in that format ?

I would be grateful for any advice offered regarding this.

Thanks in advance.

John Clarke
0
johnclarke
Asked:
johnclarke
1 Solution
 
ozoCommented:
print join'-',(localtime((stat $givenfile)[9])=~/(\w+) (\d+).* (\d+)/)[1,0,2];
0
 
toastgoddessCommented:
I'm assuming you're running under Unix, though the following code will run under either Unix or Win32.

"There is no way under standard Unix to find a file's creation time" (direct from the _Perl Cookbook_!) but since this is an upload directory presumably either the last modification time or the inode change time will do.

The subroutine can be invoked within a script as

last_modified($file)

where $file holds the name of the file you want to check.

sub last_modified {
#
#  get the filename that was passed as an argument
#
    my $file = shift;
#
#  stat returns a list of file attributes.  last modified
#  time, or mtime, is index 9 in the list.  To use the
#  inode change time instead, substitute 10 for 9 in the
#  next line.
#
    my $last_write = (stat($file))[9];
#
#  The time stat returns is in seconds since the epoch.
#  localtime converts epoch time into a list of seconds,
#  minutes, hours, and so forth.  We'll pull out the
#  values we're interested in:
#
    my ($day, $month, $year) = (localtime($last_write))[3,4,5];

#
#  Almost there - the $month variable is a number, so we'll
#  create an array of month names:
#
    my @monthnames = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct
                        Nov Dec);
#
#  Now printf prints a nicely-formatted DD-MMM-YYYY date
#  for us.  We use the $day value returned by stat, use
#  $month as an index into @monthnames, and add 1900 to
#  the $year value returned by stat.  Don't panic at the
#  sight of the 1900 - years returned by stat are not
#  necessarily two digits long, and this code will continue
#  to work after the year 2000.
#
    printf ("%02d-%3s-%04d\n", $day, $monthnames[$month], $year+1900);

}

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now