Reputation: 1849
We've got a time in MySQL datetime format, like:
$time = date("Y-m-d H:i:s");
$period = "+1 month";
Now we want to calculate 'N Days' after this time, the thing is that I want the new calculated time also in MySQL datetime format, so I've created this function:
// From a date to period date based on date
function fromTime($time, $period){
$date = DateTime::createFromFormat( 'Y-m-d H:i:s', $time);
$date->modify($period);
return $date->format('Y-m-d H:i:s');
}
It works fine on my localhost since I'm using PHP > 5.3, but on my real server it's not working and I'm getting this error:
Fatal error: Call to undefined method DateTime::createFromFormat() in /home/blah/public_html/includes/functions.php on line 38
Line 38 is fromTime
function.
How I need to change this function so it works also on PHP < 5.3
UPDATE: OP is looking for solution that works in < 5.2 to be precise.
Upvotes: 0
Views: 161
Reputation: 5589
Instead of using DateTime class, you can use the older builtin date manipulation functions like strtotime()
.
function fromTime($time, $period) {
return date("Y-m-d H:i:s", strtotime($period, strtotime($time)));
}
Upvotes: 1
Reputation: 421
Pls Try It
$d = new DateTime( date("Y-m-d H:i:s") );
$d->modify( 'next month' );
echo $d->format( 'Y-m-d H:i:s' ), "\n";
Upvotes: 0
Reputation: 7054
I think everything is valid 5.2 except the DateTime::createFromFormat
. There is nothing non standard about the date format. I'd say remove that line and instanciate the dateTime
object like:
$date = new DateTime($time);
What PHP version do you need it to be compatible with? < 5.2?
Upvotes: 0