tags:

views:

136

answers:

8

Is there a way to change a date from

1985-12-15

to

1985-12

without using a regular Expression?

+7  A: 
<?php echo date('Y-m', strtotime('1985-12-15')); ?>

That should do it.

This will, using strtotime, convert 1985-12-15 to a unix timestamp. The date function then takes a second parameter timestamp on which to format the date.

alexn
+4  A: 

Convert the date to time via strtotime() then use date() to output in correct date format, like so:

<?php    
echo date("Y-m",strtotime("1985-12-15"));
?>
Jamie Bicknell
Bugger, beaten to it by 6 seconds
Jamie Bicknell
A: 
$myDate = date('Y-m',strtotime('1985-12-15'));
echo $myDate // prints '1985-12'
inkedmn
A: 

not best to substr($date,0,strrpos($date,'-')); ?

thatd be cheapest ?

n00b32
+3  A: 

Maybe I'm just stupid, but if you only want the beginning of that date, stored as a string, can't you just use substr to extract the 7 characters at the beginning of that string ?

A bit like this, for instance :

$input = '1985-12-15';

$output = substr($input, 0, 7);
var_dump($output);

Which does give you :

string '1985-12' (length=7)

No need for any date-manipulation related function, in this case -- and this will probably be even faster/cheapier that parsing the string to a date and all that.

(Yeah, I know, premature optimisation ^^ )

Pascal MARTIN
woot if 1985-1-1 :D
n00b32
@noob52 : well noted -- the question, in this case, is "will that date be stored as 1985-01-01, or as 1985-1-1 ?" ; I would use the first solution, and I admit I didn't think about the second one ^^
Pascal MARTIN
A: 

If you think a regular expression isn't "cheap", then time functions will almost certainly be even more expensive: you would need to convert the string into a time value, then format it back into a string...

jcinacio
A: 

do you have that time value already in a array or do you whant such a like output come from the date function?

Lopoc
A: 

If you are not sure how the date will be formated, you should use the strtotime function, otherwise its probably as easy to do if the format is yyyy-mmm-dd or yy-m-d.

$datearray = explode('-',$date);
echo $datearray[0].'-'.$datearray[1];
ivarne