pnj Posted November 2, 2006 Share Posted November 2, 2006 Here is the code. The goal is to count the number of days between two days passed in mysql yyyy-mm-dd format.[code]function date_sub ($d1, $d2) { $t1 = mktime (0, 0, 0, substr($d1, 5, 2), substr($d1, 8, 2), substr($d1, 0, 4)); $t2 = mktime (0, 0, 0, substr($d2, 5, 2), substr($d2, 8, 2), substr($d2, 0, 4)); $diff = ($t1 - $t2); return ($diff / (60 * 60 * 24));}/**** END FUNCTION *************************/echo date_sub ("2006-03-01", "2006-02-01") . '<br>';echo date_sub ("2006-04-01", "2006-03-01") . '<br>';echo date_sub ("2006-05-01", "2006-04-01") . '<br>';echo date_sub ("2006-06-01", "2006-05-01") . '<br>';echo date_sub ("2006-07-01", "2006-06-01") . '<br>';[/code]The code outputs this:[code]2830.9583333333303130[/code]What's with the 30.958 days in March instead of 31? I realize I can get around the problem with (int)($d+0.5), but I wonder if this strange behavior implies that I am using the date function incorrectly...Thankspnj Quote Link to comment https://forums.phpfreaks.com/topic/25917-mktime-says-30958-days-in-month-of-march/ Share on other sites More sharing options...
Daniel0 Posted November 2, 2006 Share Posted November 2, 2006 I don't know why it would do that. You can use the round function to fix it.What I think would be a better solution would be to use timestamps: [code]<?phpfunction date_sub($d1,$d2){ return round(($d1-$d2)/60/60/24,0);}echo date_sub(*timestamp one*, *timestamp two*);?>[/code] Quote Link to comment https://forums.phpfreaks.com/topic/25917-mktime-says-30958-days-in-month-of-march/#findComment-118418 Share on other sites More sharing options...
pnj Posted November 2, 2006 Author Share Posted November 2, 2006 But is there a better way to turn those mysql date fields into timestamps besides using mktime()? I don't think it's feasible to use timestamps in the database, as it is a date field that I am trying to record.cheerspnj Quote Link to comment https://forums.phpfreaks.com/topic/25917-mktime-says-30958-days-in-month-of-march/#findComment-118425 Share on other sites More sharing options...
kenrbnsn Posted November 2, 2006 Share Posted November 2, 2006 Have you looked at the [url=http://www.php.net/strtotime]strtotime()[/url] function.Ken Quote Link to comment https://forums.phpfreaks.com/topic/25917-mktime-says-30958-days-in-month-of-march/#findComment-118429 Share on other sites More sharing options...
pnj Posted November 2, 2006 Author Share Posted November 2, 2006 ah, a highly interesting function, thank you.-pnj Quote Link to comment https://forums.phpfreaks.com/topic/25917-mktime-says-30958-days-in-month-of-march/#findComment-118431 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.