Yasha Nisanov
Yasha Nisanov

Reputation: 177

PHP mktime different results based on minutes calculation

The following mktime produces a different result on the final echo.

php > echo mktime(7, 36, 0);
1406842560
php > echo mktime(7, 60 * 0.6, 0);
1406842560
php > echo mktime(7, 60 * ( 7.6 - 7.0 ), 0);
1406842500

This minute parameter is 36 for each mktime, and I've tried casting with (int) and intval, and also using the DateTime object's setTime function, but the exact same results.

This is just an example, I need the final mktime version to work as the previous two, as would be expected, because of the calculations done via variables in place of the numbers in example above.

Any ideas?

Upvotes: 4

Views: 97

Answers (2)

developerwjk
developerwjk

Reputation: 8659

Interestingly, ceil works but floor doesn't!

Work:

mktime(7, ceil(60 * ( 7.6 - 7.0 )), 0); //1406810160
mktime(7, round(60 * ( 7.6 - 7.0 )), 0); //1406810160
mktime(7, (string)(60 * ( 7.6 - 7.0 )), 0); //1406810160

Don't:

mktime(7, floor(60 * ( 7.6 - 7.0 )), 0); //1406810100
mktime(7, intval(60 * ( 7.6 - 7.0 )), 0); //1406810100
mktime(7, (int)(60 * ( 7.6 - 7.0 )), 0); //1406810100

Upvotes: 1

user2074055
user2074055

Reputation:

I don't have a great explanation as to why this is the case - I have a feeling it's to do with the value you're passing being a float, rather than an integer, so there's probably a precision issue going on in the background.

The following appears to work correctly by adding the round() function around the second parameter:

echo mktime(7, round(60 * ( 7.6 - 7.0 )), 0);

Returns 1406842560.

Upvotes: 2

Related Questions