user3118004
user3118004

Reputation: 35

PHP get date after one week and calculate the number of days left

I have a dynamic date, now what i want is that finding the date after exact one week, i have achieved that with the code below, but now i want that now many days are left for that week after date to come. i have got some sort of time stamp, but i don't know how to convert it to DAYS LEFT.

$weekDate = date( "d/m/Y", strtotime("19-05-2014") + 86400 * 7 );

echo $weekDate;// THATS PERFECT

////////////////////////////////////////////////////////////////

$future = strtotime( $weekDate ); //Future date.

$datediff = time() - $future;

$days = floor( ( ( $datediff / 24 ) / 60 ) / 60  ); //this is not perfect, returns some 

sort of timestamp

I have tried other methods which are fine, but if week completes on 26, and today is 25th it gives me 0 days left, but it should say 1 day left. please help me.

Upvotes: 0

Views: 2253

Answers (3)

user1978142
user1978142

Reputation: 7948

In your $date_diff now is less than the future date thats why its zero. Inside strtotime() function, you can directly put a relative date inside. In this case, for one week you can use +1 week or +7 days. Consider this example:

$next_week = date('d/m/Y', strtotime('19-05-2014 +1 week')); // 26/05/2014
$next_week = strtotime('19-05-2014 +7 days');
$difference = $next_week - time(); // next weeks date minus todays date
$difference = date('j', $difference);
echo $difference . (($difference > 1) ? ' days ' : ' day ') . ' left';
// should output: 1 day left

Upvotes: 2

vascowhite
vascowhite

Reputation: 18430

Use DateTime for date and time calculations.

$weekDate = new \DateTime('+ 1 week');
$future = new \DateTime('+ 3 days');
$daysLeft = $weekDate->diff($future)->days;
echo $daysLeft; //4

See it working.

Reference http://php.net/datetime

Upvotes: 0

Fabic
Fabic

Reputation: 508

Alright. I did something. Here's the code

$startDate = strtotime("19-05-2014");

$endDate = $startDate + 604800;

$diff = ($endDate - time()) / 60 / 60 / 24;

if ($diff < 1 && $diff > 0) {
    $days = 1;
} else {
    $days = floor($diff);
}

echo $days;

The problem you have with getting "1 day" if the date is tomorrow is the floor method. strtotime() gives you the time at 0 a.m. if you don't set it by your own. Because of that the difference between now and tomorrow is less than 1 which is 0 if you floor that. I created an if-clause for that. But that will give you "1 day" for today and "1 day" for yesterday (last 2 days before the final date). If you want that better, you have to specify time in your initial date (19-05-2014).

Upvotes: 1

Related Questions