Jump to content

Subtracting Times in PHP? *SOLVED*


bpops

Recommended Posts

Hi all,

I'm interested in subtracting two times for a comment system I'm working on. It's the typical kind of comment system you often see on blogs and such where a comment will have "Posted 26 seconds ago" or "Posted 36 minutes ago" or even "Posted 94 days ago". I have the date and time stored (XX-XX-XXXX for date and XX:XX:XX for time) in the mysql db already, just need to compare it to the current time. I'm just not sure how to go about this.

How do I merge the date and time for a single number to compare? Then what's the easiest way to look at whether I should be giving seconds, minutes, hours or days? Thanks!
Link to comment
https://forums.phpfreaks.com/topic/21835-subtracting-times-in-php-solved/
Share on other sites

Just in case anyone else is interested in doing this, I modified the DateDiff function that I found on that website just a bit. So now I just give the function two times (both in the Unix epoch format). It returns a string that tells you how much time has elapsed between the two. The units scale appropriately (perfect for comment system and blogs).

[code=php:0]
Function DateDiff($date1,$date2) {
// get the number of seconds between the two dates
$timedifference = $date2 - $date1;
// determine appropriate scale
if($timedifference >= 3153600)
$interval = 'year';
else if($timedifference >= 604800)
$interval = 'week';
else if($timedifference >= 86400)
$interval = 'day';
else if($timedifference >= 3600)
$interval = 'hour';
else if($timedifference >= 60)
$interval = 'minute';
else
$interval = 'second';
// calculate elapsed time
switch ($interval) {
case 'year':
$retval = bcdiv($timedifference,31536000);
break;
case 'week':
$retval = bcdiv($timedifference,604800);
break;
case 'day':
$retval = bcdiv($timedifference,86400);
break;
case 'hour':
$retval =bcdiv($timedifference,3600);
break;
case 'minute':
$retval = bcdiv($timedifference,60);
break;
case 'second':
$retval = $timedifference;
break;
}
// add 's' if plural (e.g. 1 second, 2 seconds)
if($retval != 1)
$interval .= 's';
return $retval.' '.$interval;
}
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.