Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between two datetimes

I am using PHP and MySQL, and want to calculate date time difference between two datetimes. I have a message table, in that table createdate is one field. I want to find out day and time difference from current date in the format 1 day 2 hours ago. What is the best way to go about this?

like image 800
Sanjay Khatri Avatar asked Apr 09 '11 04:04

Sanjay Khatri


1 Answers

Use PHP's built in date functions:

<?php
    $start_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
    $end_time = "Y-m-d H:i:s"; // fill this in with actual time in this format

    // both of the above formats are the same as what MySQL stores its
    // DATETIMEs in

    $start = new DateTime($start_time);
    $interval = $start->diff(new DateTime($end_time));

    echo $interval->format("d \d\a\y\s h \h\o\u\r\s");
  • DateInterval documentation
  • DateTime::diff documentation
like image 84
Jimmy Sawczuk Avatar answered Oct 06 '22 00:10

Jimmy Sawczuk