我想以DateTime
格式提醒%d/%m-%Y'
今天的日期,但我得undef
。
我做错了什么?
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use DateTime ();
use DateTime::Format::Strptime;
my $now = DateTime->now;
my $p = DateTime::Format::Strptime->new(
pattern => '%d/%m-%Y',
time_zone => 'UTC',
);
my $dt = $p->parse_datetime($now);
print Dumper $dt;
答案 0 :(得分:4)
它可以写成:
#!/usr/bin/env perl
use strict;
use warnings;
use DateTime ();
my $now = DateTime->now( 'time_zone' => 'UTC' );
print $now->strftime('%d/%m-%Y');
答案 1 :(得分:3)
通常,DateTime格式化程序将解析字符串并从DateTime对象格式化字符串。 - > parse_datetime将从字符串中为您提供DateTime对象,而> format_datetime将为您提供DateTime对象的字符串。如果您要使用格式化程序来反序列化和重新序列化日期,则可以通过几种不同的方式使用它:
use strict;
use warnings;
use Data::Dumper;
use DateTime;
use DateTime::Format::Strptime;
use 5.012;
my $now = DateTime->now(time_zone => 'local');
say $now; ### '2011-07-01T08:22:03' - converted to string with default formatter
my $p = DateTime::Format::Strptime->new(
pattern => '%d/%m-%Y',
time_zone => 'UTC',
);
say $p->format_datetime($now); ### use the parser against a DateTime
### '01/07-2011'
$now->set_formatter($p); ### Set the parser as the default string
### formatter for the DateTime object
say $now; ### '01/07-2011' -- from formatter
### Or set it at object construction
my $now2 = DateTime->now( time_zone => 'local',
formatter => $p,
);
say $now2; ### '01/07-2011' - from formatter