Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use sprintf to add zeros to a variable? (ie make 1 become 01)

Status
Not open for further replies.

Mizugori

Programmer
Joined
May 21, 2007
Messages
56
Location
US
I am trying to compare a timestamp to a variable which has been set by three drop down menus, from which the user picked a month, day, and year. now my code does this:

Code:
my $date = $year.'-'.$month.'-'.$day;

The problem is, timestamps have a zero in the tens place if the number is smaller than 10, so 1 shows up as 10. This causes a problem because the timestamp

2005-01-27

will not match even if the user has selected January 27, 2005, because my $date will be set to:

2005-1-27

I know I should be able to use sprintf to pad $date with zeros, but the syntax is bogging me down.. can anyone help me??

thanks!!
 
Code:
my $date = printf "%4d-%02d-%02d", $year, $month, $day;
 
That's sprintf brigmar

Code:
[url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]$date[/blue] = [url=http://perldoc.perl.org/functions/sprintf.html][black][b]sprintf[/b][/black][/url] [red]"[/red][purple]%4d-%02d-%02d[/purple][red]"[/red], [blue]$year[/blue], [blue]$month[/blue], [blue]$day[/blue][red];[/red]

- Miller
 
thanks guys it works!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top