代码之家  ›  专栏  ›  技术社区  ›  Anders

如何更改Perl中日期时间值的时区?

  •  6
  • Anders  · 技术社区  · 15 年前

    使用此功能:

    perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
    

    它将返回一个epochtime,但只在gmt中返回。如果我希望结果是gmt+1(哪个是系统本地时间(tz)),我需要更改什么?

    事先谢谢,

    安德斯

    6 回复  |  直到 8 年前
        1
  •  4
  •   Community CDub    8 年前

    基于UTC,epochtime只有一个标准定义,而不同时区没有不同的epochtime。

    如果你想找到 offset between gmtime and localtime 使用

    use Time::Local;
    @t = localtime(time);
    $gmt_offset_in_seconds = timegm(@t) - timelocal(@t);
    
        2
  •  6
  •   Otto    12 年前
    use DateTime;
    my $dt   = DateTime->now;
    $dt->set_time_zone( 'Europe/Madrid' );
    
        3
  •  2
  •   William Pursell    15 年前

    你只需要设定时区。尝试:

    env TZ=UTC+1 perl -e 'use Time::Local; print timelocal("00","00","00","01","01","2000"),"\n";'
    
        4
  •  2
  •   Greg Bacon    15 年前

    Time::Local::timelocal 是的反义词 localtime .结果将出现在主机的本地时间中:

    $ perl -MTime::Local -le \
        'print scalar localtime timelocal "00","00","00","01","01","2000"'
    Tue Feb  1 00:00:00 2000

    你想要 gmtime 与之相对应的 本地时间 ?

    $ perl -MTime::Local' -le \
        'print scalar gmtime timelocal "00","00","00","01","01","2000"'
    Mon Jan 31 23:00:00 2000

    你想换个方向吗? 本地时间 与之相对应的 通用时间 是吗?

    $ perl -MTime::Local -le \
        'print scalar localtime timegm "00","00","00","01","01","2000"'
    Tue Feb  1 01:00:00 2000
        5
  •  2
  •   Kaoru    15 年前

    虽然时间::本地是一个合理的解决方案,但最好使用更现代的面向对象的datetime模块。下面是一个例子:

    use strict;
    use DateTime;
    my $dt = DateTime->now;
    print $dt->epoch, "\n";
    

    对于时区,可以使用datetime::timezone模块。

    use strict;
    use DateTime;
    use DateTime::TimeZone;
    
    my $dt = DateTime->now;
    my $tz = DateTime::TimeZone->new(name => "local");
    
    $dt->add(seconds => $tz->offset_for_datetime($dt));
    
    print $dt->epoch, "\n";
    

    CPAN链接:

    DateTime

        6
  •  0
  •   palik    8 年前

    另一个基于 DateTime::Format::Strptime

    use strict;
    use warnings;
    use v5.10;
    use DateTime::Format::Strptime;
    
    my $s = "2016-12-22T06:16:29.798Z";
    my $p = DateTime::Format::Strptime->new(
      pattern => "%Y-%m-%dT%T.%NZ",
      time_zone => "UTC"
    );
    
    my $dt = $p->parse_datetime($s);    
    $dt->set_time_zone("Europe/Berlin");
    say join ' ', $dt->ymd, $dt->hms; # shows 2016-12-22 07:16:29