如何在Perl中优雅地以RFC822格式打印日期?

Tom*_*ner 18 perl datetime date rfc822

如何在Perl中优雅地以RFC822格式打印日期?

njs*_*jsf 30

use POSIX qw(strftime);
print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
Run Code Online (Sandbox Code Playgroud)


yst*_*sth 15

DateTime套件为您提供了多种不同的方式,例如:

use DateTime;
print DateTime->now()->strftime("%a, %d %b %Y %H:%M:%S %z");

use DateTime::Format::Mail;
print DateTime::Format::Mail->format_datetime( DateTime->now() );

print DateTime->now( formatter => DateTime::Format::Mail->new() );
Run Code Online (Sandbox Code Playgroud)

更新:为某个特定时区留出时间,在now()中添加一个time_zone参数:

DateTime->now( time_zone => $ENV{'TZ'}, ... )
Run Code Online (Sandbox Code Playgroud)


Dan*_*ité 5

它可以用strftime,但它%a(日)和%b(月)用当前语言环境的语言表示.

来自man strftime:

%a根据当前区域设置缩写的工作日名称.
%b根据当前区域设置的缩写月份名称.

邮件中的日期字段必须仅使用这些名称(来自rfc2822日期和时间规范):

day         =  "Mon"  / "Tue" /  "Wed"  / "Thu" /  "Fri"  / "Sat" /  "Sun"

month       =  "Jan"  /  "Feb" /  "Mar"  /  "Apr" /  "May"  /  "Jun" /
               "Jul"  /  "Aug" /  "Sep"  /  "Oct" /  "Nov"  /  "Dec"
Run Code Online (Sandbox Code Playgroud)

因此,可移植代码应切换到C语言环境:

use POSIX qw(strftime locale_h);

my $old_locale = setlocale(LC_TIME, "C");
my $date_rfc822 = strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time()));
setlocale(LC_TIME, $old_locale);

print "$date_rfc822\n";
Run Code Online (Sandbox Code Playgroud)