black_belt
black_belt

Reputation: 6799

How to find out the month from a date when the date format is - day-month-year?

Would you please kindly tell me how to find out the month from a date when the date format is like following?

    01/12/2011

  Day-Month-year

Thanks :)

Upvotes: 0

Views: 550

Answers (2)

piotrekkr
piotrekkr

Reputation: 3226

Try

$v = explode('/', $date);
echo $v[1];

In PHP 5.4+:

$month = explode('/', $date)[1];

I also wrote that:

$t = strtotime($date);
echo date('m', $t);

but this won't work since date in format 12/10/2012 is treated as English date so second part 10 is treated as day of month not as month number. You should use

DateTime::createFromFormat('d/m/Y', $date)

as @PeeHaa suggest.

Upvotes: 2

PeeHaa
PeeHaa

Reputation: 72729

$thedate = '01/12/2011';
$date = DateTime::createFromFormat('d/m/Y', $thedate);

print($date->format('m'));

PHP's DateTime object only is available from PHP 5.2 and createFromFormat() from PHP 5.2.3.

Alternatively you could fake the timestamp to be the correct format:

$thedate = str_replace('/', '-', '01/12/2011');

$date = strtotime($thedate);
print(date('m', $date));

Upvotes: 3

Related Questions