tags:

views:

297

answers:

4

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

+3  A: 

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 );
r3zn1k
It outputs `Dec` for me here http://writecodeonline.com/php/
Sarfraz
I forgot the $ @$timestamp and, now it works.
r3zn1k
The second parameter of `substr` is length, not end position. You can also seek from the end, using `substr($month, -2, 2)`.
nikc
@nikc Thx, you're right. I didn't check his substr.
r3zn1k
Why would you say `2 = Jan`? It is not true. In this particular case it is true, but *only* because you create the timestamp for day 0, and not day 1, which means the last day of the previous month. `mktime(0, 0, 0, $monthNr, 1)` will create a timestamp for the 1st day of the month, current year.
nikc
+4  A: 

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

echo date('M', strtotime($month . '01'));
mexique1
02 represents Feb not May
Roland
Sure ! Try my code, it works.
mexique1
@Roland: 02 = Jan, 03 = Feb, ..., 13 = Dec
r3zn1k
@r3zn1k Thank you
Roland
A: 
$mydate = "201002";
date('M', mktime(0, 0, 0, substr($mydate, 4, 2), 1, 2000)); 
Oops
A: 

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]; 

But it's hard to expect a programmer under php tag...

Col. Shrapnel
Poor August and September. :(
salathe
It should be substr($strange_date,4,2), because the third parameter is the lenght...
r3zn1k
thanks. 7 more to go
Col. Shrapnel