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

Hi All, I would like to use the current system date to append to a file name. i.e. If the date is 6/10/2003, and I have a file name File.txt. I would like to be able to rename the file to File6102003.txt I would appreciate any help. Thanks in advance.

Replies are listed 'Best First'.
Re: Date Convert
by davorg (Chancellor) on Jun 10, 2003 at 13:51 UTC

    Easiest way is probably to use strftime from POSIX.pm.

    use POSIX 'strftime'; my $today = strftime '%d%m%Y', localtime; # assume filename is in $name $name =~ s/(\.\w+)$/$today$1/;

    I'd also recommend using a more meaningful date format (like YYYY-MM-DD) as people from the US often misread DD-MM-YYYY as MM-DD-YYYY for some reason.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      +++++++ Brilliant decision, especially s/(\.\w+)$/$today$1/.

      Live and learn ;-)
            
      --------------------------------
      SV* sv_bless(SV* sv, HV* stash);
      
Re: Date Convert
by halley (Prior) on Jun 10, 2003 at 13:46 UTC

    Homework or real task? What have you considered? What have you read? Where have you searched the web? What have you tried? Got any code you thought would work, but didn't?

    And I would recommend the format of YYYY-MM-DD for dates, and prepend them to filenames, instead of some digit soup following the name, if you would like them to sort by date naturally.

    --
    [ e d @ h a l l e y . c c ]

Re: Date Convert
by DrHyde (Prior) on Jun 10, 2003 at 14:40 UTC
    Is 6/10/2003 in October or June? If the date is 1/11/2003 (regardless of whether you use little-endian or middle-endian format) does 1112003 mean 1/11/2003 or 11/1/2003, both of which are valid in both systems?

    Pay heed to the advice to use YYYY-MM-DD format. Not only does it lend itself to convenient sorting as another Monk noted, it's also unambiguous and an international standard. If you have a single-digit day or month, pad it with zero using sprintf or one of the other solutions presented here.

      Is 6/10/2003 in October or June?

      It's in October obviously. There's no other sane interpretation. Thinking it is in June would just be madness.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

Re: Date Convert
by nite_man (Deacon) on Jun 10, 2003 at 13:54 UTC
    One way to do it:
    my $fname = '/your/path/File.txt'; if(-e $fname) { my ($name, $pref) = split /\./, $fname; my @date = localtime; rename $fname, $name.$date[3].($date[4]+1).($date[5]+1900).'.'.$pre +f; }
          
    --------------------------------
    SV* sv_bless(SV* sv, HV* stash);