Simple PHP Dates

I’ve seen people ask how to do future and past dates,  so here’s what I use.

function doDate($when, $days){
if($when=='past'){
echo date('l, F j, Y', time() - 86400 * $days);
}else if($when=='future'){
echo date('l, F j, Y', time() + 86400 * $days);
}
}

Usage: <?php doDate(‘[past/future]‘,[number of days]); ?>

Example: <?php doDate(‘past’,3); ?>

This will show a date either in the past or future for whatever days you want.

It gets the job done.

Tags: , , ,

6 Responses to “Simple PHP Dates”

  1. itchy 22. Dec, 2009 at 4:03 pm #

    nice matt, thats an elegant solution.

  2. David Jeffries 22. Dec, 2009 at 8:09 pm #

    Why make it so complex?

    function doDate($days){
    echo date(‘l, F j, Y’, time() + 86400 * $days);
    }

    Then you can pass it a positive (future) or negative (past) number.

    I would also consider returning the date instead of echoing it out. Perhaps a showDate() function should be created which echos the result of the doDate function. This way, the doDate function could be reused if you ever needed to store the result in a variable, for example.

  3. Matt Fraser 23. Dec, 2009 at 8:40 pm #

    Your way is better.
    I like it with strings just so its easier to glance at (I’m not very bright right)
    It’s only used on LP’s hence the echo, or else yeah it would return a var

  4. Volomike 31. Dec, 2009 at 8:51 am #

    There’s a faster, newer, more prescribed way to do this in PHP5 and it uses plain English, almost.

    function doDate($nInterval) {
    $dDate = new DateTime();
    $dDate->modify(“$nInterval”);
    return $dDate->format(‘Y-m-d H:i:s’);
    }

    echo doDate(‘+4 days’);
    echo “\n”;
    echo doDate(‘-5 hours’);
    echo “\n”;
    echo doDate(‘+2 weeks’);
    echo “\n”;
    echo doDate(‘-5 weeks -2 days’);

    See how much more power it gives you? No messy 86400 stuff to add in, and it handles years, months, weeks, days, hours, minutes, and seconds, going backwards and forwards.

    Note I could have also used your preferred formatting format for the .format() call of: ’l, F j, Y’.

    The only trouble would be — and you only see this when you turn on a Strict Standards error mode in your pages — is that you should set the date and time first somewhere in your code to a particular timezone so that it doesn’t just guess your server time. This is done easily, however, like so, and should be called before running doDate(). It only needs to be called once and then all subsequent doDate() calls will work fine.

    // change to your timezone or use “UTC” for Universal Coordinated Time if that’s your thing.
    date_default_timezone_set(‘America/New_York’);

    (I do PHP for a living, working from home.)

  5. Matt Fraser 31. Dec, 2009 at 11:04 am #

    Nice that looks a lot more efficient

  6. Riley Pool 05. Feb, 2010 at 8:18 pm #

    Thanks for the code Matt. I was looking for a simple solution like this the other day.

Leave a Reply