Question

I have a date stored into a string variable as such: Sun Jun 02 08:54:12 EDT 2013. How can I convert this into a date variable to compare the time difference between the current date and the date provided. Thanks!

Was it helpful?

Solution

Use the DateTime class to compare the current date with the timestring. Once you have the DateTime objects you can easily get the difference using the method DateTime::diff(). It will return a DateInterval object that can be printed using it's format() method.

$dt = new DateTime('Sun Jun 02 08:54:12');
$now = new DateTime();

if($now > $dt) {
    $difference = $now->diff($dt);
    echo $difference->format('The time is %H hours %I minutes %S seconds in the past');
} else if ($now < $dt) {
    $difference = $dt->diff($now);
    echo $difference->format('The time is %H hours %I minutes %S seconds in the future');
} else {
    echo 'the time is now';
}

Note: Of course you'll have to extend the output in a way that it displays the difference in years, months and days additionally. I didn't that in the example, because I'm lazy ... aehhmm because the string would get too long for the example ... ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top