So in a recent project, I had to handle some formatted dates. Piece of cake right? Date handling in PHP is a snap with date() and strtotime(). In fact, I’ve often said that the date functions are the best part of PHP, so I’ll have this knocked out in no time.
Well, maybe not.
I’m handling credit card expiration dates specifically in this case. Usually, the user is given a choice of months and years in a drop-down list. “That’s too annoying,” I thought, “It’s much faster to just type it in and let PHP handle the date formatting.” The expected input format is mm/yy so, of course I proceed with something like this for storage:
Done and done! Hmm…until I tested it.
Turns out that strtotime() doesn’t like the format mm/yy. So maybe if I enter it as mm/yyyy it’ll be ok. No, not ok there either. “That’s kind of odd,” I thought. So I head to the function’s page to see if there are any user comments on it and I see this:
strtotime returns time() for any string that begins with “eat” (case insensitive)
Hrm? What sense does that make? It could be an abbreviation, but what does EAT stand for? Well, I’m getting off point by now, so I set up some tests to see what I could figure out with strtotime():
2/8/2010 => 02/2010
2.8.2010 => 08/2010
2010-2-8 => 02/2010
2/8/10 => 02/2010
2.8.10 => 02/2009
10-2-8 => 02/2010
2/10 => 02/2009
2/2010 => false
2010-02 => 02/2010
Weird huh? 2/8/10 gives the correct year, but 2.8.10 doesn’t? 2/10 gives the wrong year (because it’s assuming the date given is 2/10/current_year), but 2/2010 fails? Yet, 2010-02 works. I’m kinda baffled by this, but I’m sure there are some eccentricities to this function since it handles stuff like “tomorrow +20 years.”
So, since I’m asking for a specific format, I decide to switch to strptime(). As with all PHP functions I seldom use, I check to make sure it’s available in the version I’m using. Since 5.1? Ok, whew! Wait…really? This is a pretty basic date function that’s provided in the C run-time. Why did it take so long to get in to PHP? Ok that’s beside the point — but I look a little down the page and see:
Note: This function is not implemented on Windows platforms.
What? Why? It’s like I’m in bizarro world or something. Am I crazy?
Ok — it still doesn’t matter, there are still things here that need to be done, I just can’t test it on my machine at work. No biggie. So I check strftime() to see about the formatting codes. Hmm. Wait a second…again… strftime() has been available since PHP 4? Why it — what — not — both — ? Arghhh!
I must be crazy. I must be. If I’m not, PHP will surely drive me there.