加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何解析Perl中的日期和转换时区?

发布时间:2020-12-15 21:23:21 所属栏目:大数据 来源:网络整理
导读:我使用了Perl中的 localtime函数来获取当前日期和时间,但需要解析现有日期。我有一个GMT日期格式如下:“20090103 12:00”我想解析成一个日期对象,我可以工作,然后将GMT时间/日期转换为我当前的时区,这是目前的东部标准时间。所以我想把“20090103 12:00
我使用了Perl中的 localtime函数来获取当前日期和时间,但需要解析现有日期。我有一个GMT日期格式如下:“20090103 12:00”我想解析成一个日期对象,我可以工作,然后将GMT时间/日期转换为我当前的时区,这是目前的东部标准时间。所以我想把“20090103 12:00”转换为“20090103 7:00”任何信息,如何做到这将非常感谢。

解决方法

因为Perl内置的日期处理接口是笨拙的,你绕过了一半的变量,更好的方法是使用 DateTime或 Time::Piece.日期时间是所有的歌唱,所有的跳舞Perl日期对象,你它可能最终想要使用它,但Time :: Piece更简单,完全足够这项任务,具有运输与5.10的优势和技术是基本相同的两者。

这里是使用Time :: Piece和strptime的简单,灵活的方式。

#!/usr/bin/perl

use 5.10.0;

use strict;
use warnings;

use Time::Piece;

# Read the date from the command line.
my $date = shift;

# Parse the date using strptime(),which uses strftime() formats.
my $time = Time::Piece->strptime($date,"%Y%m%d %H:%M");

# Here it is,parsed but still in GMT.
say $time->datetime;

# Get your local time zone offset and add it to the time.
$time += $time->localtime->tzoffset;

# And here it is localized.
say $time->datetime;

这里是旁路的方式,对比。

由于格式是固定的,正则表达式会很好,但如果格式改变,你必须调整正则表达式。

my($year,$mon,$day,$hour,$min) = 
    $date =~ /^(d{4}) (d{2}) (d{2}) (d{2}):(d{2})$/x;

然后将其转换为Unix时代(1970年1月1日以来的秒数)

use Time::Local;
# Note that all the internal Perl date handling functions take month
# from 0 and the year starting at 1900.  Blame C (or blame Larry for
# parroting C).
my $time = timegm(0,$min,$mon - 1,$year - 1900);

然后回到你当地的时间。

(undef,$year) = localtime($time);

my $local_date = sprintf "%d%02d%02d %02d:%02dn",$year + 1900,$mon + 1,$min;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读