I'm working on a Perl program at work and stuck on (what I think is) a trivial problem. I simply need to build a string in the format '06/13/2012' (always 10 characters, so 0's for numbers less than 10).
Here's what I have so far:
use Time::localtime; $tm=localtime; my ($day,$month,$year)=($tm->mday,$tm->month,$tm->year);
localtime() function in Perl returns the current date and time of the system, if called without passing any argument.
use v5. 10; use POSIX qw(strftime); my $date = '19700101'; my @times; @times[5,4,3] = $date =~ m/\A(\d{4})(\d{2})(\d{2})\z/; $times[5] -= 1900; $times[4] -= 1; # strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1) say strftime( '%d-%b-%Y', @times );
You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier. Replaced by.
Learn the perldoc command. Show activity on this post. To get the day, month, and year, you should use localtime : my($day, $month, $year)=(localtime)[3,4,5];
You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.
use POSIX qw(strftime); my $date = strftime "%m/%d/%Y", localtime; print $date;
You can use Time::Piece
, which shouldn't need installing as it is a core module and has been distributed with Perl 5 since version 10.
use Time::Piece; my $date = localtime->strftime('%m/%d/%Y'); print $date;
output
06/13/2012
You may prefer to use the dmy
method, which takes a single parameter which is the separator to be used between the fields of the result, and avoids having to specify a full date/time format
my $date = localtime->dmy('/');
This produces an identical result to that of my original solution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With