Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How to get TZ difference?

by hsweet (Pilgrim)
on Jun 28, 2003 at 12:04 UTC ( #269848=note: print w/replies, xml ) Need Help??


in reply to How to get TZ difference?

One way might be to use Perl's localtime and gmtime functions. Something like this should work.
$local=(localtime)[2]; $gmt=(gmtime)[2]; $diff=$gmtime-$local; #depending on which side of the line you are on

Time flies like an arrow, fruit flies like banannas

Replies are listed 'Best First'.
Re: Re: How to get TZ difference?
by sgifford (Prior) on Jun 28, 2003 at 16:56 UTC
    This doesn't work when localtime and gmtime are on different days (ie, in zone GMT+4 between 8:00pm and 11:59pm). Here's a fixed version:
    #!/usr/bin/perl @local=(localtime); @gmt=(gmtime); $diff=$gmt[2]-$local[2]; if ($gmt[5] > $local[5] || $gmt[7] > $local[7]) { $diff += 24; } elsif ($gmt[5] < $local[5] || $gmt[7] < $local[7]) { $diff -= 24; }
      This is a little shorter and more confusing.
      @local=(localtime(time+$off_h*60*60)); @gmt=(gmtime(time+$off_h*60*60)); $diff=$gmt[2]-$local[2] + ($gmt[5] <=> $local[5] || $gmt[7] <=> $local[7])*24;
        Hi,

        Thanks for your idea. But let me ask you what is $off_h here? And I found that correct result occurs when I subtract $gmt[2] from $local[2]:

        $diff=$local[2]-$gmt[2] + ($gmt[5] <=> $local[5] || $gmt[7] <=> $local[7])*24;

        --dda

      thanks for the correction

      Time flies like an arrow, fruit flies like banannas

      you forgot to compare the months in case when we have last day of the month, around midnight it will return inccorect results
        perl -e 'print ( ( (localtime)[2] - (gmtime)[2] + 12 ) % 24 - 12 )'

        ...works across midnight, end of month, etc without all those pesky conditionals. Works because perl has a useful definition of modulo operator (%) for negative operands, but beware this can be compromised in certain situations. See perlop#Multiplicative-Operators.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://269848]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2022-09-25 14:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer my indexes to start at:




    Results (116 votes). Check out past polls.

    Notices?