Making time for mktime; Counting down in PHP

Monday, October 3, 2005

There’s plenty of date and time functions for PHP… there’s mktime() which returns a UNIX timestamp, time() returns current Unix timestamp, strtotime which formats a string into a unix timestamp etc etc… Maybe I’m just dumb, but I’m getting a tad bit confused here… isn’t there a best practice of sorts?

Not only is there plenty of functions performing similar things, there’s a bunch of converters for different timezones, and probably a whole different set of stuff to deal with timestamps coming from MySQL databases.

And all I wanted was a dead simple countdown script, a “days until”-kind of thing. Well, anyhow, I think I got it working, If anybody sees this, please let me know if this is insane or not:

function countdown($year=2006,$month=1,$day=12) {
    $event = mktime(7, 0, 0, $month, $day, $year);
    $now = time()+7200; // +2 hours, my "local timezone"
    $diff = ceil(($event - $now) / (1 * 24 * 60 * 60));
    return $diff;
}

Patched together from php.net comments and some trial-and-error, all it does is to count down the days until the arrival… all -1050 of them…

hmm… reading what I just posted, I see the relative dates-plugin being used on my own site… Guess I could have used that instead of spending half an hour reading about date and time functions. lesson learned. onwards.

2 comments so far. Go ahead, write something

You can follow any responses to this entry through the RSS feed

For the year, month and day variables passed to the function, what format should they be in?

2005, 03, 14?

2005, 3, 14?

05, 3, 14?

#1 Ben 22 Nov 05

they should be in: 2005, 3, 14…
countdown(2005,3,14);

#2 bjorn 14 Dec 05

Type here: