mktime() weirdness

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ArKay
Forum Newbie
Posts: 1
Joined: Sat Sep 14, 2002 3:52 pm

mktime() weirdness

Post by ArKay »

Hello,

I am using the mktime() function to insert datetime values into a flat textfile.
The value are encoded with base64, and when I read them out and format them (date("d.m.Y", $erg) . " " . date("H:i", $erg)), I get the following strange values:

mktime(07, 33, 49, 03, 09, 2001) -> 28.02.2001 07:33
mktime(08, 23, 38, 03, 09, 2001) -> 28.02.2001 00:23
mktime(22, 47, 25, 04, 24, 2001) -> 24.04.2001 22:47 (correct)
mktime(20, 49, 01, 07, 04, 2001) -> 04.07.2001 20:49 (correct)

Why do I get wrong results in the first 2 cases?

Rainer
SimonMayer
Forum Commoner
Posts: 32
Joined: Wed Sep 09, 2009 6:40 pm

Re: mktime() weirdness

Post by SimonMayer »

I know this is old, but I stumbled across it and I was intrigued to see this happen.

According to the PHP manual, you would need to enter the days and months in single digit format date("j") and date("n")

From the PHP manual mktime page: int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )

I do not know why some of the dates are working. I am guessing that by coincidence the 'invalid' input has not caused a problem. All in all, it seems a strange limitation, but using single digit figures appears to rectify the problem.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: mktime() weirdness

Post by requinix »

Ooh. Yeah. Old.

A number that starts with 0 is in octal. That's base 8, as opposed the regular base 10 we're all used to.

In base 8 the only valid digits are 0-7. Using 8 or 9 is invalid and PHP gives you back nothing (zero).

Code: Select all

echo 01, 02, 03, 04, 05, 06, 07, 08, 09;
// 123456700

Code: Select all

mktime(07, 33, 49, 03, /* 09 is invalid*/ 0, 2001)
mktime will correct for invalid numbers (can't have a day 0), so 3/0 = one day before 3/1 = 2/28 (in 2001).

Code: Select all

mktime(/* 08 is invalid */ 0, 23, 38, 03, /* 09 is invalid */ 0, 2001);
// 2001-03-00 00:23:38 -> 2001-02-28 00:23:38
SimonMayer
Forum Commoner
Posts: 32
Joined: Wed Sep 09, 2009 6:40 pm

Re: mktime() weirdness

Post by SimonMayer »

Thanks tasairis. That's a very clear explanation.

I could see that it wasn't valid, but now I can see why it treats the month number in such a way.
Post Reply