Elitmiar
Elitmiar

Reputation: 36899

Convert month number to month short name

I have a variable with the following value

$month = 201002; 

the first 4 numbers represent the year, and the last 2 numbers represent the month. I need to get the last 2 numbers in the month string name eg. Feb

My code looks like this

<?php echo date('M',substr($month,4,6)); ?>

I can I go about to obtain the month name

Upvotes: 11

Views: 71970

Answers (6)

Hossam Ghareeb
Hossam Ghareeb

Reputation: 7123

You can use the DateTime Class to get a Date data structure using date string and format. Then get a date string with any format like this:

$month = 201002; 
$date = DateTime::createFromFormat('Yd', $month);  
$monthName = $date->format('M'); // will get Month name

Upvotes: 1

Gaurav Porwal
Gaurav Porwal

Reputation: 513

This may help you..

  $month = substr($month, -2, 2);
  echo date('M', strtotime(date('Y-'. $month .'-d'))); 

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 158007

Being a programmer, and even knowing nothing of PHP data magic, I'd made it

$month = intval(substr($input_date,4,2));
$mons = explode(" ","Zer Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
echo $mons[$month]; 

Upvotes: -2

oliver31
oliver31

Reputation: 2533

The second parameter of date is a timestamp. Use mktime to create one.

$month = 201002;
$monthNr = substr($month, -2, 2);

$timestamp = mktime(0, 0, 0, $monthNr, 1);
$monthName = date('M', $timestamp );

Upvotes: 7

OlimilOops
OlimilOops

Reputation: 6797

$mydate = "201002";
date('M', mktime(0, 0, 0, substr($mydate, 4, 2), 1, 2000)); 

Upvotes: 0

mexique1
mexique1

Reputation: 1693

Append "01" and strtotime will be able to parse the string :

echo date('M', strtotime($month . '01'));

Upvotes: 27

Related Questions