7
Dec
2011
Perl: Format date strings
By Eric Downing. Filed in Perl, Programming, Scripting, Utilities |The other day I had a requirement to fill in a date value while creating an entity in ClearQuest. The field that was required was a date and was formatted as “mm/dd/yyyy hh:MM::SS AM|PM”. I used the localtime function to return the date and used sprintf to format the date to the proper output.
The reason I used sprintf was that for hours, months and days less 10 the output was 1 digit instead of two and the input was not allowed. The %02d states that the digits used will be a minumum of 2 in this case.
Here is the sample program I wrote to test the expected output:
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime; # formatted just by concatenating output my $datestring = $mon . "/" . $mday . "/" . $year . " " . $hour . ":" . $min. ":" . $sec ; # formatted using sprintf to ensure proper digit counts are output my $datestring2 = sprintf("%02d/%02d/%04d %d:%02d:%02d %s",$mon,$mday,1900 +$yea r,$hour,$min,$sec, $hour >= 12? "PM" : "AM"); print $datestring; print $datestring2;