Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP datetime add one second [duplicate]

Tags:

php

datetime

Possible Duplicate:
PHP date time

Trying to add one second to a datetime that is input by the user $values['start_date_'.$j.'-'.$i] is a valid datetime string, however the following code is throwing an error

$priceStart = date('Y-m-d H:i:s',strtotime($values['start_date_'.$j.'-'.$i]));
date_modify($priceStart, '+1 second');
$priceStart =date_format($priceStart, 'Y-m-d H:i:s');

The error is "date_modify() expects parameter 1 to be DateTime, string given in... on line..." same error follows for date_format()

what is the correct syntax for this?

like image 945
Mike Avatar asked May 11 '12 19:05

Mike


2 Answers

Use a DateTime object instead. It's much more powerful and easy for this one.

$priceStart = new DateTime("@" . strtotime($values['start_date_'.$j.'-'.$i]));
$priceStart->modify("+1 second"); //You're pretty much done here!
echo $priceStart->format("Y-m-d H:i:s"); //Just to see the result.
like image 156
Madara's Ghost Avatar answered Oct 20 '22 06:10

Madara's Ghost


date() gives you a string. date_modify needs a DateTime object.

The easiest way to do what you want is simply adding one to the value returned by strtotime():

$priceStart = date('Y-m-d H:i:s',strtotime($values['start_date_'.$j.'-'.$i]) + 1);

Or, you can create a DateTime object:

$priceStart = new DateTime('@' . strtotime($values['start_date_'.$j.'-'.$i]));

and the rest of your code should start working.

like image 40
ceejayoz Avatar answered Oct 20 '22 08:10

ceejayoz