Karthik
Karthik

Reputation: 1488

Dates in php Sunday and Saturday?

i have one date.

example : $date='2011-21-12';

data format :yyyy-dd-mm;

IF date is Saturday or Sunday.

if Saturday add 2 day to the given date.

if Sunday add 1 day to the given date. ?

Upvotes: 4

Views: 12989

Answers (7)

DanceSC
DanceSC

Reputation: 521

I just subtracted the difference from 8 an added it to the days.

if(date('N', strtotime($date)) >= 6) {
        $n = (8 - date("N",strtotime($date)));
        $date = date("Y-m-d", strtotime("+".$n." days");
}

Upvotes: 0

sbrbot
sbrbot

Reputation: 6469

For sundays date('w',$date) will return 0, so the simplest test code is:

if(!date('w',strtotime($date)) { ... } //sunday

Upvotes: 0

Wige
Wige

Reputation: 3918

In a single line of code:

if (date('N', $date) > 5) $nextweekday = date('Y-m-d', strtotime("next Monday", $date));

If the day of week has a value greater than 5 (Monday = 1, Sat is 6 and Sun is 7) set $nextweekday to the YYYY-MM-DD value of the following Monday.

Editing to add, because the date format may not be accepted, you would need to reformat the date first. Add the following lines above my code:

$pieces = explode('-', $date);
$date = $pieces[0].'-'.$pieces[2].'-'.$pieces[1];

This will put the date in Y-m-d order so that strtotime can recognize it.

Upvotes: 11

472084
472084

Reputation: 17894

$date = '2011-21-12'
$stamp = strtotime($date);
$day = date("l", $stamp);
if ($day == "Saturday"){
    $stamp = $stamp + (2*+86400);
}elseif($day == "Sunday"){
    $stamp = $stamp + 86400;
}
echo date("Y-d-m", $stamp);

The only reason i can think why this wouldnt work is strtotime not recognising that data format...

Upvotes: 1

Jacob
Jacob

Reputation: 8344

The DateTime object can be really helpful for anything like this. In this case.

$date = DateTime::createFromFormat('Y-d-m', '2011-21-12');
if ($date->format('l') == 'Sunday')
    $date->modify('+1 day');
elseif ($date->format('l') == 'Saturday')
    $date->modify('+2 days');

If you want to get the date back in that format.

$date = $date->format('Y-d-m');

Upvotes: 2

Adnan
Adnan

Reputation: 26360

What about this:

$date='2011-21-12';

if (date("D", strtotime($date)) == "Sat"){
   $new_date = date("Y-m-d", strtotime("+ 2 days",$date);
}

else if (date("D", strtotime($date)) == "Sun"){
   $new_date = date("Y-m-d", strtotime("+ 1 day",$date);
}

Upvotes: 2

alexn
alexn

Reputation: 59012

You can use the date and strtotime functions for this, like so:

$date = strtotime('2011-12-21');
$is_saturday = date('l', $date) == 'Saturday';
$is_sunday = date('l', $date) == 'Sunday';

if($is_saturday) {
    $date = strtotime('+2 days', $date);
} else if($is_sunday) {
    $date = strtotime('+1 days', $date);
}

echo 'Date is now ' . date('Y-m-d H:i:s', $date);

Upvotes: 3

Related Questions