tags:

views:

731

answers:

7

Using File::stat we can get the ctime of a given file. My question is how to change the ctime, which means the inode change time in seconds since the epoch, to a normal time representation like "2009-08-26 17:28:28". Is there any build-in or module can solve this task?

A: 
use DateTime;
$dt = DateTime->from_epoch( epoch => $epoch );

The datetime object then contains the representations you require, e.g. $year = $dt->year; etc. In scalar context you get a nice human-readable representation, e.g.

$epoch = 123456789;
$dt = DateTime->from_epoch( epoch => $epoch );
print $dt;

1973-11-29T21:33:09
ire_and_curses
A: 

There's an example in Time::localtime perldoc for using it's ctime() to do this sort of thing.

use File::stat;
use Time::localtime;

my $date_string = ctime(stat($file)->ctime);
cms
A: 
use File::stat;
use Time::CTime;

$file = "BLAH BLAH BLAH";

$st = stat($file) or die "No $file: $!";
print strftime('%b %o', localtime($st->ctime));

#Feb 11th, for example.
butterchicken
+5  A: 

The most standard way is to use POSIX module and it's strftime function.

use POSIX qw( strftime );
use File::stat;

my $stat_epoch = stat( 'some_file.name' )->ctime;
print strftime('%Y-%m-%d %H:%M:%S', localtime( $stat_epoch ) );

All these markers like %Y, %m and so on, are defined in standard, and work the same in C, system "date" command (at least on Unix) and so on.

depesz
strftime is the way to go. Not much fuss, and lots of flexibility in output format.
Kevin
A: 

As you can see from the number of answers here, you have lots of options. I like the Date::Format module:

#!/usr/bin/perl
use strict;
use warnings;

use Date::Format;
use File::Stat;

my $fs = File::Stat->new( '.vimrc' );
my $mtime = $fs->ctime();
print time2str( "changed in %Y on %B, %o at %T\n", $mtime );
innaM
+2  A: 

If all you want is a human-readable representation, then

print scalar localtime stat($filename)->ctime;

will do the job. This prints something like "Wed Jun 10 19:25:16 2009". You can't influence the format, though. If you want the time in GMT, use "scalar gmtime" instead.

This is a special behaviour of localtime and gmtime in scalar context.

trendels
A: 

First, are you really using File::Stat rather than File::stat? If so, and if you have 5.8 or greater, switch to File::stat.

perldoc localtime

  • localtime EXPR
  • localtime

    Converts a time as returned by the time function to a 9-element list with the time analyzed for the local time zone.

...

In scalar context, localtime() returns the ctime(3) value:

Once you realize that localtime can take an argument, then your mind opens up to all the other possibilities mentioned in this thread.

#!/usr/bin/perl

use strict;
use warnings;

use File::stat;

my $stat = stat 't.pl';

print "$_\n" for $stat->ctime, scalar localtime($stat->ctime);
Sinan Ünür
Holy crap! I edited the question and replaced File::stat with File::Stat. Undoing that change now.
innaM