On 07/05/2010 06:46 AM, Dave Cross wrote:
> On 07/05/2010 04:19 AM, Lyle wrote:
>> Hi All,
>> I've just produced the following code, I'm sure there is a simple was
>> to have done it, but it's very late (that's my excuse and I'm sticking
>> to it). It works, but I thought I'd post it here for criticism.
>>
>> Requirement was to produce date formatted as "YYYY-MM-DD HH:MM:SS ±OO:OO".
>>
>>
>> use Time::Local 'timegm';
>> my $gmtime = time;
>> my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
>> localtime($gmtime);
>> my $localtime = timegm($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
>>
>> my $adjust = {
>> hours => 0,
>> mins => 0,
>> prefix => '+',
>> };
>> if ( $gmtime> $localtime ) {
>> my $adjust_secs = $gmtime - $localtime;
>> my $adjust_mins = $adjust_secs / 60;
>> $adjust->{hours} = int( $adjust_mins / 60 );
>> $adjust->{mins} = $adjust_mins - $adjust->{hours} * 60 if (
>> $adjust_mins % 60 );
>> $adjust->{prefix} = '-';
>> }#if
>> elsif ( $localtime> $gmtime ) {
>> my $adjust_secs = $localtime - $gmtime;
>> my $adjust_mins = $adjust_secs / 60;
>> $adjust->{hours} = int( $adjust_mins / 60 );
>> $adjust->{mins} = $adjust_mins - $adjust->{hours} * 60 if (
>> $adjust_mins % 60 );
>> }#elsif
>>
>> my $formatted = sprintf("%04d-%02d-%02d %02d:%02d:%02d %s%02d:%02d",
>> $year, $mon, $mday, $hour, $min, $sec, $adjust->{prefix},
>> $adjust->{hours}, $adjust->{mins});
>
> POSIX::strftime is your friend.
>
> $ perl -MPOSIX=strftime -E'say strftime "%Y-%m-%d %H:%M:%S %z", localtime'
> 2010-07-05 06:44:39 +0100
On further reflection, it strikes me that my output isn't exactly what
you asked for. You wanted the timeszone as "+01:00" and I gave you "+0100".
The command line "date" command has the "%:z" escape sequence that gives
what you want.
$ date +%:z
+01:00
But that's apparently not supported by POSIX.pm.
$ perl -MPOSIX=strftime -E'say strftime "%:z", localtime'
%:z
But there's still no need to resort to the coding pyrotechnics you used
above when a simple substitution fixes the problem.
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use POSIX qw[strftime];
$_ = strftime '%Y-%m-%d %H:%M:%S %z', localtime;
s/(\d\d)$/:$1/;
say; # 2010-07-05 11:01:33 +01:00
Hope that helps,
Dave...
_______________________________________________
BristolBathPM mailing list
[email protected]
http://mailman.bristolbath.org/mailman/listinfo/bristolbathpm