Reputation: 47
I am trying to take difference of two time. I have used diff function for that and now I want to transfer output of var_dump to array or variable so that I am able to print remaining time. My code is written below. How to retrieve below output to array or variable?
$val1 = '2014-03-18 10:34:09';
$var2 = date("Y-m-d H:i:s");
$datetime1 = new DateTime($val1);
$datetime2 = new DateTime($val2);
var_dump($datetime1->diff($datetime2));
My output is show below
object(DateInterval)#3 (8) {
["y"]=>
int(0)
["m"]=>
int(11)
["d"]=>
int(1)
["h"]=>
int(6)
["i"]=>
int(17)
["s"]=>
int(23)
["invert"]=>
int(0)
["days"]=>
int(338)
}
Upvotes: 2
Views: 1330
Reputation: 72415
You use function date()
to format the current time then pass the result to the constructor of class DateTime
that parses the date to components just to get back the current timestamp.
There is no need make it do this hard work. If you need a DateTime
object that contains the current date & time all you need to do is to create a new instance of DateTime
and pass no parameters to its constructor:
$datetime2 = new DateTime();
Now, about the difference between two dates. Using DateTime::diff()
is the correct way to do it, indeed, but using var_dump()
doesn't help and converting it to array (or other strange things) is not needed.
The value returned by DateTime::diff()
is an object of type DateInterval
. It provides public access to its properties and it also provides you the method DateInterval::format()
that is a nice way to produce readable string out of the value it encapsulates.
$val1 = '2014-03-18 10:34:09';
$datetime1 = new DateTime($val1);
$datetime2 = new DateTime('now');
$diff = $datetime1->diff($datetime2);
echo("It's been ".$diff->days.' days since '.$val1.".\n");
echo($diff->format("%a days, %h hours, %i minutes and %s seconds to be more precise.\n"));
Upvotes: 1
Reputation: 171
It seems to me that you still need to manipulate this variable, so I would suggest that you assign the return value to a variable, instead of trying to get the string value from var_dump.
$diff = $datetime1->diff($datetime2)
- as per @panther.
If your goal is to capture the string output, then you can use $valueInString = print_r($diff, true);
although its output is slightly different from var_dump.
P.S. I think you misspelled $var2
as it should be $val2
Upvotes: 0
Reputation: 18601
Simply you have to write following it will return array.
$data = $datetime1->diff($datetime2); //Return Object
$data = (array) $datetime1->diff($datetime2); //Return Array
Object Output
$data->y = 0 //year
$data->m = 11 //month
$data->d = 1 //day
$data->h = 1 //hour
$data->i = 8 //minute
$data->s = 33 //second
Array Output
$data['y'] = 0 //year
$data['m'] = 11 //month
$data['d'] = 1 //day
$data['h'] = 1 //hour
$data['i'] = 8 //minute
$data['s'] = 33 //second
Upvotes: 2