Craig Wilson
Craig Wilson

Reputation: 461

strtotime PHP for date numerical value + 1 week

I have a day value of 1 through 7 where 1 is Monday and 7 is Sunday.

I need to get a strtotime value of the appropriate day NEXT week.

For example:Today is Tuesday 13th November.

My day value is "2" so strtotime should return the appropriate value for Tuesday 20th November. My day value is "1" so strtotime should return the appropriate value for Monday 19th November. My day value is "5" so strtotime should return the appropriate value for Friday 23rd November.

I'm hoping this can be done with just a few built in PHP functions (strtotime(+1week+something))? If not I will attempt to code some comparison checks!

Thanks!

Upvotes: 1

Views: 11751

Answers (5)

sberry
sberry

Reputation: 132028

function dayNextWeek($num) {
  return date('Y-m-d', strtotime("+1 week +" . ($num - date('w'))  . "days"));
}

And to test:

foreach (range(1, 7) as $i) {
  echo $i . ' ' . dayNextWeek($i) . "\n";
}

OUTPUT

1 2012-11-19
2 2012-11-20
3 2012-11-21
4 2012-11-22
5 2012-11-23
6 2012-11-24
7 2012-11-25

Upvotes: 3

Teena Thomas
Teena Thomas

Reputation: 5239

Try:

 $day_nxt_week = date('N', strtotime(date('Ymd') . '+1 week'));
 print_r($day_nxt_week);

Demo

Upvotes: 0

Abdul Haseeb
Abdul Haseeb

Reputation: 548

Hopefully, This should work for you.

<?php
$array = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
$your_value = 2;
$str = 'next ' . $array[$your_value -1];
echo date('D d M Y', strtotime($str));

?>

http://codepad.org/OIrzRxpl

Upvotes: 0

rcravens
rcravens

Reputation: 8388

function getNext($dow)
{
    $now = intval(date('N'));

    $toAdd = $dow - $now;
    if($toAdd<=0)
    {
        $toAdd += 7;
    }

    return date('r', strtotime('+'.$toAdd.'day'));
}

Upvotes: 0

Martin Lyne
Martin Lyne

Reputation: 3065

Not tested extensively:

$givenDayNumber = 1;             // Your value here
$date = new DateTime();          // Today (reference point)
$currentDayOfWeek = date('N');   // This is 1 = Monday, see php date manual for more options
$diff = $givenDayNumber- $currentDayOfWeek; // Difference between given number and todays number
$date->modify('+ '.$diff.' day'); // Subtract difference
$date->modify('+ 1 week');        // Add a week
echo $date->format('d/m/Y');      // Output

Codepad here for fiddling: http://codepad.org/7SylbJOX

Upvotes: 0

Related Questions