While working with a CJ run reports script i needed to convert “month name” into “month number” so i could store it in the database in date format. After doing some cleaning stuff i was ending with the month name, a three character string as “Jan”,”Mar”,”Apr” etc. Here is the quick work around i applied to get the month number automatically from the month name.
$month_name = "Jan"; //which i get from file name (Range_from_1_Jan_2009_to_3_Mar_2009.txt)
$month_number = "";
for($i=1;$i<=12;$i++){
if(strtolower(date("M", mktime(0, 0, 0, $i, 1, 0))) == strtolower($month_name)){
$month_number = $i;
break;
}
}
Now as php snippet code line 5 date(“M”, mktime(0, 0, 0, 1, 1, 0))) returns a three letter represantion of month name i get month “1″ if i pass $month_name=”Jan” and so on. If i had full month name like “January” i could make it work by replacing “M” with “F” where “F” format parameter is a full represantion of year name.
Special Note: Do not forget to see user comments down the page to find even smarter solutions





devswa
April 11, 2012 at 6:15 pm
@Trev Simmons thank you…
Trev Simmons
September 8, 2011 at 5:01 pm
All very well but you can do it in a single line without any need for programming loops….
$monthname ="September"; //insert usercode here$monthnum = date("n", strtotime("01-".$monthname."-2011 00:00:00"));Will work for 3-letter short names as well as full names. The day year and time in the code is irrelevant as you are just extracting the month info.
Hope that helps.
Arvind K.
September 8, 2011 at 6:18 pm
Thanks you Trev Simmons. That is very smart solution!
Mizu
October 29, 2010 at 11:18 pm
@Mike, thanks for your comment! I’m using that instead..
Mike
October 17, 2010 at 3:22 am
Even easier:
$monthName = 'Jan';$m = array('Jan'=>1, 'Feb'=>2.... );
$monthNumber = $m[$monthName];
JDkeriya
May 25, 2010 at 9:13 am
Thanks for providing this.It’s a great solution.
Dan Price
April 14, 2010 at 2:39 pm
Great bit of code! Much better than using an array of the months.
One point:
“for($i=1;$i< =12;$i++){ ”
shouldn’t have a space between “<” and “=”, so should be:
“for($i=1;$i<=12;$i++){”
Thanks!
admin
April 14, 2010 at 4:23 pm
@Dan Price – Thanks for pointing this out. Fixed. In fact my wp post editor had not been saving the space between < and =. I wrote HTML equivalent for “<” i.e. “<” this time and it worked! Thanks again!
vidya
November 17, 2009 at 6:45 am
“if(strtolower(date(“M”, mktime(0, 0, 0, $i, 1, 0))) == strtolower($month)){ ”
here “strtolower($month)” shoulb be strtolower($month_name)
admin
November 18, 2009 at 6:17 pm
@vidaya. Thanks for pointing this out. Correction made!