Reputation: 1
This perl script produces a datestamp and timestamp. Is there a simple way to display the time in a 12 hour format with AM/PM displayed?
use DateTime;
use DateTime::TimeZone;
my $tz = DateTime::TimeZone->new( name => 'Pacific/Honolulu' );
my $dt = DateTime->now(time_zone =>'Pacific/Honolulu');
my $offset = $tz->offset_for_datetime($dt);
$timestamp = $dt->hms(':');
$datestamp = $dt->mdy('/');
print "$datestamp at $timestamp\n";
Upvotes: 0
Views: 1331
Reputation: 1
#!/usr/local/bin/perl
use POSIX qw(strftime);
my $datestring = strftime "%a %b %e %H:%M:%S %Y %P", localtime;
printf "date and time - $datestring\n";
my $datestring = strftime "%a %b %e %H:%M:%S %Y %P", gmtime;
printf "date and time - $datestring\n";
Upvotes: -2
Reputation: 385657
Most date-time modules will provide access to the C function strftime
or a re-implementation of it. In format specifications provided to strftime
, you can use the following patterns:
%I
: The hour as a decimal number using a 12-hour clock.%l
: The hour as a decimal number using a 12-hour clock. Single digits are preceded by a blank.%p
: Either "AM" or "PM".%P
: Either "am" or "pm".DateTime objects have a method called strftime
. For example,
$ perl -e'
use DateTime qw( );
my $now = DateTime->now( time_zone => "local" );
CORE::say $now->strftime("%Y/%m/%d %I:%M:%S %p %z");
'
2019/06/02 09:45:37 PM -0400
As @Nilesh Bhimani tried to point out, the DateTime module is rather heavy, and it's not required for this task (especially if you want to use local time or UTC) because the POSIX module provides strftime
as well. For example,
$ perl -e'
use POSIX qw( strftime );
my $now = time;
CORE::say strftime("%Y/%m/%d %I:%M:%S %p %z", localtime($now));
'
2019/06/02 09:45:37 PM -0400
Upvotes: 4