Jump to content

Archived

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

ari_aaron

Compare dates?

Recommended Posts

How can you compare dates?

I have both of them in "Y-m-d H:i:s" format.

Share this post


Link to post
Share on other sites
how do you mean "compare"? in what way are you comparing them? just seeing if they are equal or getting the difference between them, or what?

Share this post


Link to post
Share on other sites
Use [url=http://php.net/strtotime]strtotime()[/url] on both dates, then compare the resulting timestamps.

Share this post


Link to post
Share on other sites
I want to get the diffrence in hours. Ho can I do that with the unix timestamp that [b]devbanana[/b] pointed out?

Share this post


Link to post
Share on other sites
Well, if you subtract them, the difference will be in seconds. If you divide by 3600, you should have the difference in hours.

[code=php:0]$diff = $date2 - $date1;
$hours = floor($diff / 3600);[/code]

Share this post


Link to post
Share on other sites
So why dosn't this code work?

[code]$stoday=strtotime("2006-08-25 10:47:09");
$sdate=-strtotime("2006-08-25 08:58:01");
$diff = $stoday - $sdate;
$hours = floor($diff / 3600);
echo "Hour differance:" . $hours;[/code]

It outputs:
[quote]Hour differance:642507[/quote]

Why is that? It is only 2 hours!

Share this post


Link to post
Share on other sites
[code]$stoday = strtotime("2006-08-25 10:47:09");
$sdate = strtotime("2006-08-25 08:58:01"); // negative sign removed!!
$diff = $stoday - $sdate;
$hours = floor($diff / 3600);
echo "Hour differance:" . $hours;[/code]

Share this post


Link to post
Share on other sites
you've got your second time with a negative in front of it, so you're actually adding the two times together. try writing up a simple function to do it for you, like this:
[code]
<?php
function get_hours($ts1, $ts2) {
$diff = abs(strtotime($ts1) - strtotime($ts2));
return round($diff / 3600);
}
$stoday = "2006-08-25 10:47:09";
$sdate = "2006-08-25 08:58:01";
$hours = get_hours($stoday, $sdate);
echo "Hour differance: " . $hours;
?>
[/code]

also, notice that i'm using round() instead of floor. this will give you a more accurate representation of the time. for instance, in the times you're playing with, floor() will only return 1 hour difference while ceil() or round() will give you 2.

Share this post


Link to post
Share on other sites

×

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.