0

Possible Duplicate:
convert month from name to number

I have a simple (yet interesting) query for all.

I am getting month name, in short, like Jan, Feb, etc. Now I need to convert it to month-number ( i.e., Numeric representation of a month), with leading zeros

Example: "Jan" to "01", "Dec" to "12", etc

Anyone know, how to achieve this, without using array

Thanks

Community
  • 1
  • 1
I-M-JM
  • 15,732
  • 26
  • 77
  • 103

7 Answers7

19
$month = 'Feb';
echo date('m', strtotime($month));

strtotime converts "Feb" to the timestamp for February 6th 2011 15:15:00 (at the time of writing), taking what it can from the given string and filling in the blanks from the current time. date('m') then formats this timestamp, outputting only the month number.

Since this may actually cause problems on, say, the 31st, you should fill in these blanks to be sure:

echo date('m', strtotime("$month 1 2011"));
deceze
  • 510,633
  • 85
  • 743
  • 889
2
$date = strtotime ("Jan");
print date("m", $date);

More on strtotime: PHP: strtotime - Manual

More on date: PHP: date - Manual

Anush Prem
  • 1,511
  • 8
  • 16
2

try this

$test  //whatever you getting
echo date("m",strtotime($test));

also see

http://php.net/manual/en/function.date.php

Bhanu Prakash Pandey
  • 3,805
  • 1
  • 24
  • 16
2

use this with a day and year it will covert fine:

$mon = 'Feb';
$month = date("F d Y",strtotime("$mon 31, 2010"));

it will work fine.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
John
  • 21
  • 1
1

strtotime will do the trick.

ex:

$monthName = 'Jan';

echo date('m', strtotime($monthName));
seanh
  • 214
  • 1
  • 7
1

Given that you already have your date.

$date = 'Jun';
$month = date('m', strtotime($date));
Romelus
  • 181
  • 1
  • 6
-1

This does not work for me:

$mon = 'Aug';
$month = date("F",strtotime($mon));

I get "December" ???

however, if I place this with a day and year it converts fine:

$mon = 'Aug';
$month = date("F d Y",strtotime("$mon 31, 2011"));

it works.

running PHP Version 5.1.2

Paul
  • 1,527
  • 2
  • 16
  • 24