getting number of days out of dates

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
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

getting number of days out of dates

Post by GeXus »

could someone tell me how you would get the number of days from a given date... for example on blogs, if you make a comment.. in two days.. it will say "Two Days Ago"... etc

Thanks!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Code: Select all

//just for this test.. use a real date in actuality
$test_date = strtotime('2 days ago');

$seconds_in_day = 60 * 60 * 24;

time() - $test_date = $difference;

$days = abs($difference);

echo "$days days ago";
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

OK time for me to go to bed... I'm getting scrappy:

Code: Select all

<?php

//just for this test.. use a real date in actuality
$test_date = strtotime('2 days ago');

$seconds_in_day = 60 * 60 * 24;

$difference = time() - $test_date;

$days = floor($difference/$seconds_in_day);

echo "$days days ago";

?>
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

To wrap it into a function...

Code: Select all

<?php
function get_days_since($date)
{
    $seconds_in_day = 60 * 60 * 24;

    $since_date = strtotime($date);

    $seconds_since = time() - $since_date;

    $days_since = floor($seconds_since/$seconds_in_days);

    return $days_since;
}

//Usage
$date_to_check = 'January 3, 2005';
$days =  get_days_since($date_to_check);

echo 'It has been ' . $days . ' days since ' . $date_to_check . '.';
?>
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post by GeXus »

Nice, thanks guys!
Post Reply