Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
perl如何将字符串转换为Datetime?_Perl_Datetime - Fatal编程技术网

perl如何将字符串转换为Datetime?

perl如何将字符串转换为Datetime?,perl,datetime,Perl,Datetime,我试图在perl中将字符串转换为日期,但出现了错误 use strict; use warnings; use DateTime; use Date::Manip; my $date = ParseDate("20111121"); print "today is ".$date->day_of_week."\n"; 错误 看起来包导入有问题 感谢来自模块文档的: 您需要添加中建议的代码,以便将字符串转换为日期时间对象。日期时间不分析日期。我会选择提供strtime()的核

我试图在perl中将字符串转换为日期,但出现了错误

use strict; 
use warnings;  
use DateTime;  
use Date::Manip;

my $date = ParseDate("20111121");
print "today is ".$date->day_of_week."\n"; 
错误

看起来包导入有问题


感谢来自模块文档的:


您需要添加中建议的代码,以便将字符串转换为日期时间对象。

日期时间不分析日期。我会选择提供strtime()的核心模块:


DateTime本身没有解析功能,但是有许多解析DateTime对象的工具。大多数时候,你可能会想要

或者你可以自己做

use DateTime qw( );
my ($y,$m,$d) = '20111121' =~ /^([0-9]{4})([0-9]{2})([0-9]{2})\z/
   or die;
my $dt = DateTime->new(
   year      => $y,
   month     => $m,
   day       => $d,
   time_zone => 'local',
);

我换成这个,还是不行。使用日期时间;my$dateStr='20111121';my$year=substr($dateStr,0,4);我的$month=substr($dateStr,4,2);my$day=substr($dateStr,6,2);打印$year。“/”$month。”/“$day。”\n“我的$date=DateTime->new(年=>$year,月=>$month,日=>$day,);为什么,当有一个核心模块时,人们会推荐使用DateTime进行简单的perl日期操作?(我是perl新手,这是一个值得商榷的问题)@Relequestual
DateTime
提供了计算日期持续时间(例如,两个日期之间的天数)的功能。也许它最重要的功能是与日历而不是时间一起工作。因此,您可以计算“昨天”的值,而不考虑夏令时和不存在的时间。请参阅模块文档和
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t = Time::Piece->strptime("20111121", "%Y%m%d");
print $t->strftime("%w\n");
use DateTime::Format::Strptime qw( );
my $format = DateTime::Format::Strptime->new(
   pattern   => '%Y%m%d',
   time_zone => 'local',
   on_error  => 'croak',
);
my $dt = $format->parse_datetime('20111121');
use DateTime qw( );
my ($y,$m,$d) = '20111121' =~ /^([0-9]{4})([0-9]{2})([0-9]{2})\z/
   or die;
my $dt = DateTime->new(
   year      => $y,
   month     => $m,
   day       => $d,
   time_zone => 'local',
);