【问题标题】:how can i exclude saturday and sunday when i generate dates生成日期时如何排除星期六和星期日
【发布时间】:2014-01-13 06:38:52
【问题描述】:

我正在使用我的代码生成日期,我想排除周日和周六,请在此处查看我的代码

for ($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date . ' + 1 day'))) {

$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("$date")); 
if ($from < $start_date)
    $from = $start_date;
$to = date("Y-m-d", strtotime("$date-1day + 1 week"));   
if ($to > $end_date) {
    $to = $end_date;
}
if ($from <= $to) {
    array_push($weekfrom, $from);
    array_push($weekto, $to);
}

$n = count($weekfrom);

for ($i = 0; $i < $n; $i++) {
    echo $weekfrom[$i];
}}

【问题讨论】:

  • 缺少右括号
  • 哎呀抱歉我忘了 :) 已经编辑了 :) 谢谢
  • 我不明白这一行:$to = date("Y-m-d", strtotime("$date-1day + 1 week")); //Returns the date of sunday in week。对我来说,你只是加了 6 天,它怎么变成了一个星期天?
  • 抱歉这里的评论 :) 我的代码中有错误的评论
  • 我会使用DateTimeDatePeriod 中的对象,例如this answer 这个问题也是this question 的重复问题。

标签: php date datetime


【解决方案1】:

你可以这样做。

$getDate = date('l', strtotime($date));
if ($getDate != 'Saturday' AND $getDate != 'Sunday') {
    ......
}

如果该日期不是周六或周日,则处理该事件。

【讨论】:

  • 我试图只排除星期天 :)
  • @user3189194 这不是你的问题所说的。
【解决方案2】:

只需将其添加到循环的开头即可:

if(date("w", strtotime($date)) == 0 || date("w", strtotime($date)) == 6) continue;

像这样:

for ($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date . ' + 1 day'))) {

if(date("w", strtotime($date)) == 0 || date("w", strtotime($date)) == 6) continue;

$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("$date")); //Returns the date of monday in week
if ($from < $start_date)
$from = $start_date;
$to = date("Y-m-d", strtotime("$date-1day + 1 week")); //Returns the date of sunday in week
if ($to > $end_date) {
$to = $end_date;
}
if ($from <= $to) {
array_push($weekfrom, $from);
array_push($weekto, $to);
}

$n = count($weekfrom);

for ($i = 0; $i < $n; $i++) {
echo $weekfrom[$i];
}}

【讨论】:

  • 像魔术一样工作:)...但是我可以问最后一个问题,我打算在周日和周六有一个单独的代码,我的意思是我有一个复选框来排除周六和排除周日跨度>
  • if(sunday_box_checked && date("w", strtotime($date)) == 0) 继续; if(saturday_box_checked && date("w", strtotime($date)) == 6) 继续;
  • 将这 2 个 if() 语句添加到循环的开头,它就可以工作了。如果您选中了复选框,Sunday_box_checked 和 saturday_box_checked 必须是您获得的布尔值。
  • 我已经在星期六和星期天输入了 6,但是在星期六的复选框中它不显示星期天
【解决方案3】:

我用过:

strtotime(sprintf('+%d weekday', 3));

如果现在是 9 月 15 日(星期三),则示例返回:20 sep(不包括周末)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-05
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多