Why doesn't mktime() work with double digits when a single digit is sufficient?

StackOverflow https://stackoverflow.com/questions/20435057

  •  30-08-2022
  •  | 
  •  

Вопрос

I'm fairly new to PHP, so forgive me if this is a stupid question.

I tried to run mktime() on my site and, because I'm still getting familiar with the syntax, ran something like this:

echo date('h:i:s M-d-Y', mktime(12, 00, 00, 12, 08, 2013) );

Which I was surprised to find returned this:

12:00:00 Nov-30-2013

When what I was expecting was this:

12:00:00 Dec-08-2013

I eventually figured out that the "08" was the problem and it should just be "8".

Given that mktime() is capable of making some on-the-fly corrections and assumptions (such as example #2), why didn't it simply correct "08" to "8"? This is especially confusing to me since it handles double 0's just fine. Is this a feature, a bug, or simply an idiosyncrasy of the language?

Also, why did it "correct" to Nov 30 as opposed to some other date? Given the above examples, I would have expected Jan 01.

Это было полезно?

Решение

This isn't an issue with mktime, but with how PHP interprets literal numbers.

In PHP, when a literal number is prefixed with a zero, e.g. 01 or 08 it is interpreted as octal, see http://www.php.net/manual/en/language.types.integer.php similar to how the 0x prefix denotes hexadecimal literal numbers.

Note that 08 is actually invalid, as octal numbers have the digits 0-7, PHP's documentation states that "If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.", so 08 becomes 0, hence why it snaps to 30th November.

Другие советы

Numbers starting with a leading 0 like 08 are octal notation; except 08 is invalid octal so it is treated as a value of 0.

As there is no 0th day in month 12, it takes 1 from the 1st december to give the last day of the previous month, 30th november

Numbers with a leading zero evaluate to octal numbers (base 8): http://www.php.net/manual/en/language.types.integer.php

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top