in reply to Date formats

Super Search would have given you lots and lots of options ....

here is one way:

#!/usr/bin/perl use strict; my($day, $month)=(localtime)[3,4]; $month++; if ($month < 10) { $month = "0" . $month; } if ($day < 10) { $day = "0" . $day; } my $date = "$month/$day"; print $date;

HTH

- f o o g o d

Replies are listed 'Best First'.
Re: Re: Date formats
by Kanji (Parson) on Jan 09, 2002 at 09:32 UTC

    Personally, I've always prefered (s)printf when padding numbers ...

    my($d,$m) = (localtime)[3,4]; my $date = sprintf("%02d/%02d",++$m,$d);

        --k.


    Update: Oops, meant to ++$m not $m++. Thanks to blakem for the catch.

Re: Re: Date formats
by rob_au (Abbot) on Jan 09, 2002 at 09:34 UTC
    Personally I find the printf function far more appealing for number and output formatting.

    my $date = sprintf("%02d%02d", (localtime)[4] + 1, (localtime)[3]); print $date, "\n";

    Reducing formatting logic clauses and conditionals within business code is a good thing from my perspective.

     

    perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

      Naughty rob_au, bad boy!

      You are calling localtime twice, which is setting yourself up for a race condition, should the code ever run on the crack of midnight of new year's eve. You could have the month from one day and the year from another.

      Yes it's highly unlikely to happen, but it would be better to

      my $date = do { my @now = localtime; sprintf("%02d%02d", $now[4] + 1, $now[3]); };

      Why invite trouble?

      --
      g r i n d e r
      print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
Re: Re: Date formats
by jlf (Scribe) on Jan 09, 2002 at 09:37 UTC
    Even simpler:

    $date = sprintf("%02d/%02d", 1+(localtime)[4], (localtime)[3]); #(localtime)[4] runs 0..11 not 1..12