NZ_Kiwis;10982063 wrote:that works for dates, but what if i'm looking for hours, minutes or seconds within the same day.
This is for datetimes, so wether it's a difference of days or seconds doesn't really matter.
$d1 = new DateTime('2011-06-12 13:00');
$d2 = new DateTime('2011-06-13 15:20');
$i = $d2->diff($d1);
echo $i->format('%Y-%M-%D %H:%I:%S');
output
00-00-01 02:20:00
Which tells you the time difference is 1 day, 2 hours, 20 minutes. If the datetimes are within the same day, there's a 2 hour 20 minute difference.
Or, if what you meant when saying you have a time() and a datestamp is that you have number of seconds since... created by time() or mktime(), and a datetime
# or, if you have a time(), i.e. seconds since... combined with a datetime
$time = 1307962800; # 2011-06-13 13:00:00, seconds since...
$d2 = new DateTime('2011-06-13 15:20:00');
$d1 = new DateTime(date('Y-m-d H:i:s', $time));
$i = $d2->diff($d1);
echo $i->format('%Y-%M-%D %H:%I:%S');
And even if you start with a datetime and an interval expressed in seconds, I still find it easier to use the built in functionality.
# or, if you have a time, datetime or whatever, combined with an interval in seconds
$time = 1307962800; # 2011-06-13 13:00:00, seconds since...
$d1 = new DateTime(date('Y-m-d H:i:s', $time));
# Clone the first datetime
$d2 = new DateTime($d1->format('Y-m-d H:i:s'));
# add your interval expressed in seconds
$d2 = $d2->add(new DateInterval('PT8400S'));
# create an interval
/* Note that you can't directly do
* $interval = new DateInterval(PT8400S');
* since $interval->format() will show 8400 seconds and 0 for anything else
*/
$i = $d2->diff($d1);
echo $i->format('%Y-%M-%D %H:%I:%S');