【问题标题】:Detect Saturday and Sunday and add x amount of days to Monday检测周六和周日并将 x 天数添加到周一
【发布时间】:2014-03-18 15:24:39
【问题描述】:

如果有人选择星期五,我希望它自动添加直到星期一的天数。 想象一下$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;
?>

【问题讨论】:

  • 到底是什么问题?你能试着更清楚你想要什么吗? (我看到星期六,星期一,加到星期五......我有点困惑;))
  • 好吧,你看,我想创建一个简单的休假系统,所以如果有人在上面提到的这两个日期申请休假,这两个日期都是星期四和星期五,所以申请这个休假的用户会星期一开始工作。我需要周一跳过周六和周日的日期。所以他们将在 2013 年 5 月 3 日开始工作。明白我的意思吗?呵呵对不起,英语不好。

标签: php date date-math


【解决方案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");

【讨论】:

    【解决方案2】:

    尝试将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;
    ?>
    

    【讨论】:

    • 你确定这段代码是正确的?我得到无限循环。
    • 不,一点也不。你没有给我们足够的东西来真正测试,所以我不知道它是否有效。为什么不在循环中添加echo 以打印出$tomorrow$getday 的值,看看为什么它没有退出。
    【解决方案3】:

    我因为愚蠢而在墙上撞了 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 2023-04-08
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多