简体   繁体   中英

Alter date if it's a weekend date PHP

I have user defined date that I add one week to. I am trying to check the user's date and see if it's a Friday,Saturday,Sunday or Monday. If it is, then I want to loop until the date is a day other than those days (pseudo code below). The code I have doesn't actually seem to work.

$date = 10/10/2012;

while (date = friday, saturday, sunday, monday) {
       $date = $date - 1;
}

Here is my code:

$postpone = date('Y-m-d', strtotime('+1 Week'));
$checkDate = date('w', strtotime($postpone));

while ($checkDate == 0 || $checkDate == 6  || $checkDate == 5 || $checkDate == 1) {
    $postpone = date_sub($postpone,date_interval_create_from_date_string("1 day"));
    $postpone = date("Y-m-d", $postpone);
    $checkDate = date('w', strtotime($postpone));
}

Below code uses the object-oriented PHP methods to accomplish this. Note that it increments the date by 1 day and you can add or subtract any interval depending on how you want to reach your target weekday.

// Make sure to set timezone when using PHP DateTime
date_default_timezone_set('UTC');

// Create a new date set to today's date
$date = new DateTime;

// Add 1 week to the date
$date->add(new DateInterval('P1W'));

// Get a numeric representation of weekday for date (0-6 0=Sunday)
$weekday = $date->format('w');

// Loop while weekday is Fri, Sat, Sun, Mon
while ($weekday > 4 || $weekday < 2) {
    // Add one day to date and get the weekday
    $weekday = $date->add(new DateInterval('P1D'))->format('w');
}

echo $date->format('Y-m-d: w');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM