sub makeDate { (my $sec, my $min, my $hour, my $mday, my $mon, my $year, my $wday +, my $yday, my $isdst) = localtime(time); $year += 1900; $sec =~ s/^(\d)$/0$1/; $min =~ s/^(\d)$/0$1/; $hour =~ s/^(\d)$/0$1/; $mon++; $mon =~ s/^(\d)$/0$1/; $mday =~ s/^(\d)$/0$1/; my $date = "$mon\_$mday\_$year\_$hour$min$sec"; return $date; }
I use this for creating very readable and sortable unique directory names for our code builds. I prepend the build information to the date string returned above. An example would be: BETA_13__10_05_05_10000

Replies are listed 'Best First'.
Re: munging the date for various uses
by Tanktalus (Canon) on Oct 05, 2005 at 19:21 UTC

    Most likely, an easier way to do this is using sprintf:

    sub makeDate { my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = l +ocaltime(time); $year += 1900; $mon++; sprintf "%02d_%02d_%04d_%02d%02d%02d", $mon, $mday, $year, $hour, $min, $sec; }
    Even better may be to use POSIX::strftime or one of the many Date modules.
    sub makeDate { require POSIX; POSIX::strftime("%m_%d_%Y_%H%M%S", localtime(time)); }

Re: munging the date for various uses
by chanio (Priest) on Oct 06, 2005 at 04:34 UTC
    Good!

    If you use POSIX::strftime you could improve your sub by accepting some integer value:

    • * If you don't receive any value or you receive 0 you would return your format.
    • * If 1, the LINUX format: yymmddhhmmss (I guess).
    • * Another format might be the MySQL one.
    • * Another one, the short format mm/dd/yy hh:mm:ss
    • * Then, the long one mmm,dd yyyy hh:mm:ss tz
    • * Create others
    The more possible outputs you could add, the more useful sub it would become. Perhaps, having your own module of useful subs to load with every code you write...
Re: munging the date for various uses
by water (Deacon) on Oct 08, 2005 at 04:46 UTC
    Rather than M D Y H M S,
    why not Y M D H M S so they sort right?
    Just a thought.

    water

      It works best for our uses that way. That's the point of this so that you can munge the date to best suit your needs.
Re: munging the date for various uses
by grinder (Bishop) on Oct 06, 2005 at 19:02 UTC

    eww, look at all those lexicals. If you can never be bothered, like me, to memorise strftime's format language, a coderef is a wonderful way of sweeping the bits under the covers.

    my $datespec = sub { sprintf '%02d_%02d_%02d_%02d%02d%02d', $_[3], $_[4]+1, $_[5]%100, reverse(@_[0..2]) }->(localtime);

    • another intruder with the mooring in the heart of the Perl