Is there a way to change a date from
1985-12-15
to
1985-12
without using a regular Expression?
Is there a way to change a date from
1985-12-15
to
1985-12
without using a regular Expression?
<?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.
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"));
?>
$myDate = date('Y-m',strtotime('1985-12-15'));
echo $myDate // prints '1985-12'
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 ^^ )
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...
do you have that time value already in a array or do you whant such a like output come from the date function?
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];