Example : add and diff method of Datetime object
Here in below example DateInterval object has the argument like P01Y01M10DHere the 01Y indicates 1 year
Here the 01M indicates 1 month
Here the 10D indicates 10 days
<?php $givendate='2001-01-01'; //add one year one month and ten days to given date $date = new DateTime($givendate); $date->add(new DateInterval('P01Y01M10D')); echo $date->format('Y-m-d') . "\n"; //remove one year one month and ten days to given date $date = new DateTime($givendate); $date->diff(new DateInterval('P01Y01M10D')); echo $date->format('Y-m-d') . "\n"; ?>Output:
2002-02-11
2001-01-01
Example : Calculate Age of a Person using Datetime object
<?php //Php Date difference - Php Datetime object $birthday="1984-10-18"; //creating object for birthday $birthday = new DateTime($birthday); //createing object for current date $currentdate = new DateTime(); //calculate age using php Datetime object method $age=$currentdate->diff($birthday); print_r($age); ?>Output:
DateInterval Object ( [y] => 27
[m] => 10
[d] => 27
[h] => 12
[i] => 38
[s] => 43
[invert] => 1
[days] => 10193
)
No comments:
Post a Comment