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

查看:45
本文介绍了如何在 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?

例如,我想解析这样的字符串:October 28, 2011 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
";

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

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

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

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