简体   繁体   English

如果是周末,则更改日期PHP

[英]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. 下面的代码使用面向对象的PHP方法来完成此任务。 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. 请注意,它将日期增加1天,您可以根据想要达到目标工作日的方式来增加或减少任何间隔。

// 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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