Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Today's Date in Perl in MM/DD/YYYY format

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); 
like image 435
dvanaria Avatar asked Jun 13 '12 18:06

dvanaria


People also ask

How do I get today's date in Perl?

localtime() function in Perl returns the current date and time of the system, if called without passing any argument.

How do I change the date format in Perl?

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 );

What is Strftime in Perl?

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.

How do I get current month in Perl?

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];


2 Answers

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; 
like image 92
Pavel Vlasov Avatar answered Oct 11 '22 00:10

Pavel Vlasov


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 


Update

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

like image 31
Borodin Avatar answered Oct 11 '22 02:10

Borodin