jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

Just at the point I thought everything was working fine I noticed the following problem (see test script):
#! /usr/bin/perl -l use strict ; use warnings ; use POSIX 'strftime'; my $a = time() ; # local time is now 12:35:00 print "input time is $a" ; print "gmtime gives: ".gmtime($a) ; my $b = strftime("%s", gmtime(int $a)) ; # %s converts date to epoch print "diff is: ".($a - $b) ;
Output
input time is 1160390100 gmtime gives: Mon Oct 9 10:35:00 2006 diff is: 3600
So, the 3600 is my problem, it should have been zero (I think)....
Any suggestions what I do wrong ? or how to get the the same result ($a) back ?

Thnx LuCa

ps maybe it will help, my localtime zone is CEST (there is a 2 hours diff with GMT)

Replies are listed 'Best First'.
Re: working with epoch seconds
by McDarren (Abbot) on Oct 09, 2006 at 11:03 UTC
    There is nothing wrong with that output at all. gmtime gives you exactly what it says - GMT time. So unless you happen to be in the GMT timezone, there will always be a difference. For example, when I run your script on my local machine I get:
    input time is 1160391190 gmtime gives: Mon Oct 9 10:53:10 2006 diff is: 28800
    My local timezone is GMT+8 hours, so the output is correct.

    Regards your local timezone being GMT+2, are you sure? Perhaps you are not taking something silly into account, like daylight savings?

    As to what you should do about that, I'm afraid that I'm a little unclear on exactly what it is that you are trying to achieve - so perhaps you need to explain that a little more.

    As a side note, you should try to avoid using $a and $b as variable names - they are special package global variables that are used by sort.

    Cheers,
    Darren :)

      very interesting that you get 28800 (8 hours). I should have had 7200, but I get 3600.
      So, the output from strftime is in the localtime zone ?
      Any suggestions how to define the output timezone ?
      Thanks a lot
      LuCa

      UPDATE: This seems todo more or less what I need:
      use DateTime ; my $now = DateTime->now->set_time_zone("UTC") ; print $now->strftime("%s", time()) ;

        Use a module:

        use strict; use warnings; use DateTime; my $dt = DateTime->now; print $dt->strftime ("%Y %m %d, %H:%M:%S %Z\n"); $dt->set_time_zone ('America/New_York'); print $dt->strftime ("%Y %m %d, %H:%M:%S %Z\n"); __END__ 2006 10 09, 11:45:55 UTC 2006 10 09, 07:45:55 EDT

        Update: Ah, you figured it out. That's great :^).

        --
        David Serrano

Re: working with epoch seconds
by ysth (Canon) on Oct 10, 2006 at 02:27 UTC
    %s seems to be a non-portable extension; I'm not sure what it is supposed to return. If you are looking for the reverse of gmtime, try Time::Local's timegm.