2

I have a countdown function that (in part) returns the "time left" until a given date/time. The value is returned as a DateInterval object and is calculated using the diff method.

//calculate countdown time
$time_diff = $countdown->diff($current);

Given that $time_diff is a DateInterval object, how would I do this?

if ($time_diff > 60) {

    //do stuff

}

I know the code above doesn't work, but how can/should I evaluate the equivalent condition ("more than 60 sec left in this DateInterval object")?

The problem is that the script used to return the "time left" as a Unix timestamp integer, and the function is utilized in a more procedural manner by a wide array of scripts in my system.

Thank you in advance for any helpful suggestions.

nmax
  • 981
  • 1
  • 11
  • 19

3 Answers3

2

You can get the individual values off the object:

if ($time_diff->s > 60) {

    //do stuff

}

See the DateInterval class structure for a full list of properties. However i think you need to look at each value on the object (days, minutes, years, etc.) and add them all up if you want the TOTAL seconds elapsed - ofcourse in your use case (a countdown timer) it may never be difference of more than seconds so that might not be necessary.

prodigitalson
  • 60,050
  • 10
  • 100
  • 114
  • In this scenario, the time diff could be several months. So I would need to get the total time remaining in seconds, rather than the individual value of seconds in the DateInterval object. This would be one way:(http://stackoverflow.com/questions/3176609/calculate-total-seconds-in-php-dateinterval), but in that case I'd probably just convert back to a Unix timestamp. – nmax Dec 19 '12 at 15:04
1

Use format().

echo $time_diff->format('%R%a days'); //'days' here, you need to change as you want

See also diff.

long
  • 3,692
  • 1
  • 22
  • 38
  • But is it possible to use the format() method to get the total amount of time remaining in seconds? – nmax Dec 19 '12 at 14:57
  • 1
    Not directly, see: http://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php – long Dec 19 '12 at 15:05
0

Because it is not possible to use the format() method on a DateInterval object to get directly the total amount of remaining time in seconds, I ended up adding a helper in my function to return the "time left" as a Unix timestamp along with the DateInterval object.

//calculate unix timetamps
$current_ts = time();
$countdown_ts = $countdown->getTimestamp();
$timestamp_diff = ($current_ts < $countdown_ts) ? ($countdown_ts - $current_ts) : 0;

Hope this is useful to others.

PS. Stackoverflow is awesome.

nmax
  • 981
  • 1
  • 11
  • 19