如何将字符串解析为Perl中的DateTime对象? [英] How to parse a string into a DateTime object in Perl?

查看:393
本文介绍了如何将字符串解析为Perl中的DateTime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 DateTime Perl模块,许多 DateTime :: Format :: 模块来解析特定类型的日期/时间格式。然而,给出一些日期/时间字符串的例子,我应该怎么弄清楚(在编程/设计时,不是在运行时)我应该使用哪个特定的模块?

I know about the DateTime Perl module, and many of the DateTime::Format:: modules to parse specific kinds of date/time formats. However given some examples of date/time strings, how can I figure out (at coding/design time, not at runtime) which specific module should I use?

例如,我想解析字符串,如: 2011年10月28日9:00 PM PDT

For example, I want to parse strings like: October 28, 2011 9:00 PM PDT

有没有一个最常见的日期/时间格式的列表,我可以查看这个,找到哪个最适合的模块?

Is there a list somewhere of the most common date/time formats where I could look this up and find which would be the most suitable module?

我也知道一些模块试图在运行时猜测每个给定字符串的格式并尽力。但是,对于敏感应用程序,我想在设计应用程序时首先确定(尽可能严格地)格式,然后使用一个模块,如果一个字符串与指定的格式不匹配,则会发出警告。

I also know about some modules which try to "guess" the format for each given string at runtime and do their best. But, for sensitive applications, I would like to determine (as strictly as possible) the format first when designing an application, and then use a module which will warn me if a string does not match the specified format.

我该怎么做?

推荐答案

DateTime::Format::Strptime 使用日期/时间字符串并将其解析为DateTime对象。

DateTime::Format::Strptime takes date/time strings and parses them into DateTime objects.

#!/usr/bin/perl

use strict;
use warnings;

use DateTime::Format::Strptime;

my $parser = DateTime::Format::Strptime->new(
  pattern => '%B %d, %Y %I:%M %p %Z',
  on_error => 'croak',
);

my $dt = $parser->parse_datetime('October 28, 2011 9:00 PM PDT');

print "$dt\n";

模式中使用的字符序列是POSIX标准。有关详细信息,请参阅man strftime。

The character sequences used in the pattern are POSIX standard. See 'man strftime' for details.

这篇关于如何将字符串解析为Perl中的DateTime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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