How do I elegantly print the date in RFC822 format in Perl?
11,057
Solution 1
use POSIX qw(strftime);
print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n";
Solution 2
The DateTime suite gives you a number of different ways, e.g.:
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() );
Update: to give time for some particular timezone, add a time_zone argument to now():
DateTime->now( time_zone => $ENV{'TZ'}, ... )
Solution 3
It can be done with strftime
, but its %a
(day) and %b
(month) are expressed in the language of the current locale.
From man strftime
:
%a The abbreviated weekday name according to the current locale.
%b The abbreviated month name according to the current locale.
The Date field in mail must use only these names (from rfc2822 DATE AND TIME SPECIFICATION):
day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
"Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
Therefore portable code should switch to the C
locale:
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";
Author by
Tom Feiner
Updated on June 03, 2022Comments
-
Tom Feiner almost 2 years
How can I elegantly print the date in RFC822 format in Perl?