过滤星期几,只显示php中的工作日

时间:2014-04-29 19:53:20

标签: php date loops time format

我正在努力创建一个只有一周工作日的下拉菜单。周一至周五。这是我的代码:

<?php if ($_SESSION['month'] == $current_month) { $current_day = date("j") + 1;} else {$current_day = 1;} ?>

<form action="" method="post">
  <select name="day" onchange="this.form.submit()">
    <option value="">-- Day --</option>
    <?php for ($i = $current_day; $i < 31; $i++) { ?>
    <option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
    <?php $tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i; 
          $weekday = date('D', strtotime($tmp_date)); 
          echo $weekday." "; ?>
    <?php echo $i; ?>
    </option>
    <?php } ?>
  </select>
</form>

这给了我当月的一周中的日子,但它显示了所有日子。我怎么才能只在星期一到星期五出现?

4 个答案:

答案 0 :(得分:1)

看起来$weekday正在为您获取名称。只需做一个nocase字符串比较:

      $weekday = date('D', strtotime($tmp_date)); 
      if (strcasecmp($weekday, 'Sun') != 0
          && strcasecmp($weekday, 'Sat') != 0){
          // Do something with valid days
      }

答案 1 :(得分:1)

<?php $tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i; ?>
<?php if (!in_array(date('w', strtotime($tmp_date)), array(0, 6)) { ?>
<option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >

      $weekday = date('D', strtotime($tmp_date)); 
      echo $weekday." "; ?>
<?php echo $i; ?>
</option>
<?php } ?>

答案 2 :(得分:1)

这比strtotime()更清晰:

$start       = DateTime::createFromFormat('Y-n-j', $_SESSION['year'].'-'.$_SESSION['month'].'-01');
$daysInMonth = $start->format('t'); 
$end         = new DateTime("+{$daysInMonth} Days");
$interval    = new DateInterval('P1D');
$period      = new DatePeriod($start, $interval, $end);
foreach ($period as $day) {
    if (in_array($day->format('D'), array('Sat', 'Sun'))) continue;
    printf('<option value="%s"%s>%s %u</option>',
         $day->format('j'),
         ($_SESSION['day'] == $day->format('j')) ? ' selected' : '',
         $day->format('D'),
         $day->format('j')
    );
}

Demo

答案 3 :(得分:0)

这对我有用:

<form action="" method="post">
  <select name="day" onchange="this.form.submit()">
    <option value="">-- Day --</option>
    <?php for ($i = $current_day; $i < 31; $i++) { 
    $tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i; 
          $weekday = date('D', strtotime($tmp_date)); 
          if (strcasecmp($weekday, 'Sun') != 0
            && strcasecmp($weekday, 'Sat') != 0){ ?>
    <option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
    <?php echo $weekday." ".$i; ?>
 <?php  } ?>