Jump to content

mktime() says 30.958 days in month of March


pnj

Recommended Posts

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]28
30.9583333333
30
31
30[/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...

Thanks
pnj
Link to comment
https://forums.phpfreaks.com/topic/25917-mktime-says-30958-days-in-month-of-march/
Share on other sites

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]<?php
function date_sub($d1,$d2)
{
return round(($d1-$d2)/60/60/24,0);
}

echo date_sub(*timestamp one*, *timestamp two*);
?>[/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.