如何在 Perl 中解析日期和转换时区? [英] How can I parse dates and convert time zones in Perl?

查看:32
本文介绍了如何在 Perl 中解析日期和转换时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Perl 中使用了 localtime 函数来获取当前日期和时间但需要解析现有日期.我有以下格式的 GMT 日期:20090103 12:00"我想将它解析为一个我可以使用的日期对象,然后将 GMT 时间/日期转换为我当前的时区,目前是东部标准时间.因此,我想将20090103 12:00"转换为20090103 7:00",我们将不胜感激.

I've used the localtime function in Perl to get the current date and time but need to parse in existing dates. I have a GMT date in the following format: "20090103 12:00" I'd like to parse it into a date object I can work with and then convert the GMT time/date into my current time zone which is currently Eastern Standard Time. So I'd like to convert "20090103 12:00" to "20090103 7:00" any info on how to do this would be greatly appreciated.

推荐答案

因为 Perl 内置的日期处理接口有点笨拙,你最终会传递六个变量,更好的方法是使用 DateTime时间::片断.DateTime 是全能、全能的 Perl 日期对象,您可能最终会想要使用它,但 Time::Piece 更简单且完全适合此任务,具有随 5.10 一起提供的优势,并且该技术是两者基本相同.

Because the Perl built in date handling interfaces are kind of clunky and you wind up passing around a half dozen variables, the better way is to use either DateTime or Time::Piece. DateTime is the all-singing, all-dancing Perl date object, and you'll probably eventually want to use it, but Time::Piece is simpler and perfectly adequate to this task, has the advantage of shipping with 5.10 and the technique is basically the same for both.

这是使用 Time::Piece 和 strptime 的简单、灵活的方法.

Here's the simple, flexible way using Time::Piece and 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;

# Create a localtime object for the same timestamp.
$time = localtime($time->epoch);

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

这里是手动方式,作为对比.

And here's the by-hand way, for contrast.

由于格式是固定的,正则表达式就可以了,但如果格式发生变化,您就必须调整正则表达式.

Since the format is fixed, a regular expression will do just fine, but if the format changes you'll have to tweak the regex.

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

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

Then convert it to Unix epoch time (seconds since Jan 1st, 1970)

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, $hour, $day, $mon - 1, $year - 1900);

然后回到您的当地时间.

And then back to your local time.

(undef, $min, $hour, $day, $mon, $year) = localtime($time);

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

这篇关于如何在 Perl 中解析日期和转换时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆