PDA

View Full Version : is this the best way to get 'today'

bazz
05-24-2009, 05:31 AM
Hi,

As you likely know, I am rubbish with posix etc.

my (\$sec, \$min, \$hour, \$mday, \$mon, \$year, \$wday, \$yday, \$isdst) = localtime (time);

\$mday = sprintf "%02d", \$mday;
\$mon = (\$mon + 1);
\$mon = sprintf "%02d", \$mon;
\$year = (\$year + 1900);

my \$today = (join ( '-' , ( \$year, \$mon, \$mday )));

print qq( today = \$today);

Is there a better way than this?

bazz

FishMonger
05-24-2009, 03:47 PM
use POSIX qw/strftime/;

my \$today = strftime("%Y-%m-%d", localtime);
print qq( today = \$today);

05-24-2009, 08:29 PM
Hi,

As you likely know, I am rubbish with posix etc.

my (\$sec, \$min, \$hour, \$mday, \$mon, \$year, \$wday, \$yday, \$isdst) = localtime (time);

\$mday = sprintf "%02d", \$mday;
\$mon = (\$mon + 1);
\$mon = sprintf "%02d", \$mon;
\$year = (\$year + 1900);

my \$today = (join ( '-' , ( \$year, \$mon, \$mday )));

print qq( today = \$today);

Is there a better way than this?

bazz

You might be bad with POSIX, but even your code can be considerably reduced with no loss of clarity:

my (\$mday, \$mon, \$year) = (localtime(time))[3,4,5];
my \$today = sprintf( "%s-%02d-%02d", ( \$year+1900, \$mon+1, \$mday ));
print qq( today = \$today);

I am not sure but I think POSIX is tied into whatever the locale is so formats like "%Y-%m-%d" might vary from computer to computer. Maybe Fish knows for sure if it is or isn't or reading the POSIX documentation might tell.

oesxyl
05-24-2009, 10:29 PM
if you want GMT you can use gmtime

use POSIX qw(strftime);

\$now_string = strftime "%Y-%m-%d", gmtime;

as Fismonger, I prefere strfime for formating, :)

best regards

bazz
05-25-2009, 04:36 AM
Thank you all.

I have got it now and shall read up again on POSIX.

bazz