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

PerlDateFormatting

Perl Problem Overview


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

Perl Solutions


Solution 1 - Perl

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;

Solution 2 - Perl

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

Solution 3 - Perl

use DateTime qw();
DateTime->now->strftime('%m/%d/%Y')   

expression returns 06/13/2012

Solution 4 - Perl

If you like doing things the hard way:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";

Solution 5 - Perl

Perl Code for Unix systems:

# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;

# Remove newline character
$current_date = substr($current_date,0,-1);

print $current_date, "\n";

Solution 6 - Perl

use Time::Piece;
...
my $t = localtime;
print $t->mdy("/");# 02/29/2000

Solution 7 - Perl

Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";

This gives you:

14.05.2014

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondvanariaView Question on Stackoverflow
Solution 1 - PerlPavel VlasovView Answer on Stackoverflow
Solution 2 - PerlBorodinView Answer on Stackoverflow
Solution 3 - PerldaximView Answer on Stackoverflow
Solution 4 - PerlcharlesbridgeView Answer on Stackoverflow
Solution 5 - PerlBharat PahalwaniView Answer on Stackoverflow
Solution 6 - PerldezhikView Answer on Stackoverflow
Solution 7 - PerlhorshackView Answer on Stackoverflow