php Weeknumber在selectbox与yearnumber

时间:2018-01-20 19:31:55

标签: javascript php html

我需要一个选择菜单(下拉菜单),周数为1到现在为止+ 10周。 所以我做了:

                <select name="weeknummer" id="weeknummer">
                <?php
                    for ($x = 1; $x <= 52; $x++) {
                        echo '<option value="'.$x.'" >week '.$x.'</option>';
                    }
                    ?>
                </select>

但是我得到的周数为1到52。 我想要的是周数1-2018,然后脚本需要检查当前的周数并增加10周。

例如,今天的选择框应为:

1-2018, 2-2018, 3-2018, 4-2018, 5-2018, 6-2018, 7-2018, 8-2018, 9-2018, 10-2018, 11-2018, 12-2018, 13-2018

下周它应该是:

1-2018, 2-2018, 3-2018, 4-2018, 5-2018, 6-2018, 7-2018, 8-2018, 9-2018, 10-2018, 11-2018, 12-2018, 13-2018, 14-2018&lt;&lt;这个添加了

但我怎么能这样做?有人能帮助我吗?

3 个答案:

答案 0 :(得分:1)

这应该是你要求的:

// Get the last week of the current year. 52 or 53.
// 28 December is always in the last week of its year. (ISO-8601)
$dt = new DateTime('December 28th');
$lastWeekOfYear = $dt->format("W");

// Get the last week in the dropdown.
$lastWeek = (date("W") + 10);

// Echo all weeks from 1 to this week plus 10 (including overflowing year boundary).
for ($x = 0; $x < $lastWeek; $x++) {
    if ($x == $lastWeekOfYear) $dt->modify("1 years");
    echo '<option value="'. $dt->format("Y") . "-" . (($x % $lastWeekOfYear) + 1) . '" >week ' . $dt->format("Y") . "-" . (($x % $lastWeekOfYear) + 1) .'</option>' . PHP_EOL;
}

答案 1 :(得分:0)

像萨尼辛格在评论中所说的那样 认为你正在寻找像这样的东西

<select name="weeknummer" id="weeknummer">
<?php
    $maxweek = (new DateTime())->format('W') + 10;
    for ($x = 1; $x <= $maxweek && $x <= 52; $x++) {
        echo '<option value="'.$x.'" >'.$x.'-2018</option>';
    }
    ?>
</select>

然而,这不允许你进入下一年。并使用硬编码年2018 如果您希望获得更大的灵活性,可以使用DateTime::modify()
例如像这样

<select name="weeknummer" id="weeknummer">
<?php
    $dt = new DateTime('January 4th'); //starting point - first week of year
    $maxdt = new DateTime('+10 weeks'); //ending point - today plus 10 weeks

    while ($dt->format('YW') <= $maxdt->format('YW')) {
        echo '<option value="'.$dt->format('W').'">'.$dt->format('W').'-'.$dt->format('Y').'</option>';
        $dt->modify('+1 week');
    }
    ?>
</select>

如果您愿意,可以使用intval()从周中删除尾随零 intval($dt->format('W'))

答案 2 :(得分:-1)

你是说这个吗?

500