检测周六和周日,并在周一添加x天

时间:2014-03-18 15:24:40

标签: php date date-math

如果有人选择星期五,我希望自动将天数添加到星期一。 想象一下$leavefrom是星期四的3-1-2014,星期五是$leaveto是3-2-2014。 $totaldays根据日期计算。因此它是2天。

<?php
$x = 0;

$date1 = str_replace('-', '/', $leavefrom);
$date2 = str_replace('-', '/', $leaveto);

while ($x < $totaldays) {

    $tomorrow = date('l', strtotime($date1 ."+1 days"));

    //$tomorrow = date("m-d-Y", strtotime( $date1 ."+1 days" ));
    $getday = date('D', strtotime($tomorrow));
    $x++;
    if ($getday == "Sunday" || $getday = "Saturday") {
        $tomorrow = date("m/d/Y", strtotime( $tomorrow ."+1 days" ));
    }
    $tomorrow = date("m/d/Y", strtotime( $tomorrow ."+1 days" ));
}

echo $tomorrow;
?>

3 个答案:

答案 0 :(得分:1)

如果您只想尝试跳过周末,请检查周末是否有$date2,如果是,请跳到下周一。

$date2 = DateTime::CreateFromFormat('n-j-Y', $leaveto);
if (in_array($date2->format('l'), array('Sunday', 'Saturday'))) {
    $date2->modify('next Monday');
}
echo $date2->format("m/d/Y");

答案 1 :(得分:0)

请尝试将if ($getday == "Sunday" || $getday = "Saturday")更改为while,然后摆脱最后的$tomorrow = ...。像这样:

<?php
$x = 0;

$date1 = str_replace('-', '/', $leavefrom);
$date2 = str_replace('-', '/', $leaveto);

while ($x < $totaldays) {

    $tomorrow = date('l', strtotime($date1 ."+1 days"));
    $x++;

    $getday = date('D', strtotime($tomorrow));
    while ($getday == "Sunday" || $getday = "Saturday") {
        $tomorrow = date("m/d/Y", strtotime( $tomorrow ."+1 days" ));
        $getday = date('D', strtotime($tomorrow));
    }

}

echo $tomorrow;
?>

答案 2 :(得分:0)

我发现解决方案是因为傻瓜在墙上爆炸3小时后发现,下面是我的代码:

while ($daysloop <= $totaldays) {
$tomorrow1 = date("m/d/Y", strtotime( $tomorrow1 ."+1 days" ));
$dayofweek = date('w', strtotime($tomorrow1));

if ($dayofweek == 0 || $dayofweek == 6) {
$weekends = $weekends + 1;
}
$daysloop++;
}

if ($totaldays == 0) {
$totaldays = $totaldays - $weekends + 1;
}
else {
$totaldays = $totaldays - $weekends;
}