Must be a better way to do this

disclaimer: I have been up way too long!

I’m playing with my blog and put a banner on the top of my page that counts the days left to the Amazon launch of Scott Sigler’s new book Ancestor. Here’s the code that I came up with, makes me think there must be a better way.

<?php
$april1st = strtotime("April 1, 2007");
$now = time();
$days_remaining = 0;

while ($april1st > $now){
    $days_remaining++;
    $now = strtotime("+1 day", $now);
}

echo ($days_remaining) ? "$days_remaining days left till you can buy Ancestor Novel" :
                                   "Ancestor Novel is available NOW!";
?>

You can see the output on my blog. Is ther

Time for some sleep… getting a plane home in a couple hours!

8 Responses to “Must be a better way to do this”

  1. HR Says:

    Erm, how about using the difference in seconds divided by the number of seconds per day?

    $days = ceil((strtotime(’April 1, 2007′) - time()) / 86400);

    if ($days > 0)
    {
    echo $days, (($days == 1) ? ‘ day’ : ‘ days’), ‘ left till you can buy Ancestor Novel’;
    }
    else
    {
    echo ‘Ancestor Novel is available NOW!’;
    }

  2. Rob... Says:

    $april1st = gmmktime(0, 0, 0, 4, 1, 2007);
    $now = gmmktime(0, 0, 0);
    $days_remaining = ($april1st - $now) / 86400;

  3. Aaron Wormus Says:

    The reason why I went with the double strtotime, was because the last time I did this was counting months, which is more complex.

  4. Rob... Says:

    For Months, I’d do something like:

    $finishYear = ‘2008′;
    $finishMonth = ‘07′;
    $thisYear = date(’Y');
    $thisMonth = date(’m');
    $numMonths = ((($finishYear - $thisYear) * 12) + $finishMonth) - $thisMonth;

    (With a possible +1 depending on how you want to count!)

  5. Derick Says:

    Everything that uses 86400 is flawed. Not every day is 86400 seconds unfortunately.

    I don’t have a solution ready though :)

  6. Maarten Manders Says:

    What about the PHP date class? Or the one in Zend Framework?

  7. HR Says:

    @Derrick: well, none of the snippets account for the user’s timezone, DST or the exact time the novel will be out but they get the job done, which I believe is the whole point of PHP right? :)

  8. HR Says:

    Damned, I misspelled your name, sorry.

Leave a Reply