By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,248 Members | 1,209 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,248 IT Pros & Developers. It's quick & easy.

Month Heading Zeros

P: 4
Hi all,
i need a variable that store the month number in the format (01-12)
this is my attempt:

$MM=@localtime[4]+1;

How can I add the heading zero if the month number if less than 10?
Jan 31 '08 #1
Share this Question
Share on Google+
3 Replies


KevinADC
Expert 2.5K+
P: 4,059
This is a very easy way to do what I think you want:

Expand|Select|Wrap|Line Numbers
  1. @months = qw(01 02 03 04 05 06 07 08 09 10 11 12);
  2. @localtime = localtime(time);
  3. $MM = $months[$locatime[4]+1];
  4. print $MM; 
or you can use sprintf function to format string with leading zeros.
Jan 31 '08 #2

numberwhun
Expert Mod 2.5K+
P: 3,503
Hi all,
i need a variable that store the month number in the format (01-12)
this is my attempt:

$MM=@localtime[4]+1;

How can I add the heading zero if the month number if less than 10?
Instead of doing that, you can do something like:

Expand|Select|Wrap|Line Numbers
  1. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  2. my $month;
  3.  
  4. if($mon <= "8")
  5. {
  6.     $mon += 1;
  7.     $month = "0" .$mon;
  8. }
  9. else
  10. {
  11.     $mon = $mon +1;
  12. }
  13.  
  14. print("Month is: $month");
  15.  
There is also another way of doing it, but the choice is yours. TIMTOWTDI ! I prefer the above as it doesn't include any extra modules.

Regards,

Jeff
Jan 31 '08 #3

eWish
Expert 100+
P: 971
or you can use sprintf function to format string with leading zeros.
Expand|Select|Wrap|Line Numbers
  1. my @localtime = localtime(time);
  2. my $formatted_month = $localtime[4]++ <= 10 ? sprintf '%02s', $localtime[4]++ :  $localtime[4]++;
  3.  
  4. print $formatted_month;
--Kevin
Feb 1 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.