FreeKB - How to print date and time in Perl using strftime
How to print date and time in Perl using strftime

Home > Search > How-to


Use the POSIX strftime module.

#!/usr/bin/perl

use warnings;
use strict;
use POSIX 'strftime';

my $date = strftime "%b %d, %Y", localtime;
my $time = strftime "%H:%M %P", localtime;

print "$date at $time\n";

 

This will produce a result in this format.

Jan 16, 2019 at 06:05 am

 

Following are commonly used options.

Option Description Example
%Y Year 2018
%y Year 18
%m Month 01
%b Month Jan
%B Month January
%d Day (with leading zero) 04
%-d Day (without leading zero) 4
%H Hour (24 hour format) 22
%I Hour (12 hour format) 10
%M Minute 56
%S Second 23
%p AM or PM AM
%P am or pm pm

 


Future / Past date

The time+ and time- options can be used to adjust the date to a future or past date. 86400 (seconds) equals one day.

my $yesterday = strftime "%b %d, %Y", localtime(time-86400);
my $tomorrow  = strftime "%b %d, %Y", localtime(time+86400);

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter fb7ea in the box below so that we can be sure you are a human.




Comments