Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

php - Months with less than 31 days omitted from list

Consider the following code that was working perfectly yesterday, but now today (30th March), it has stopped working...

<form class="date">
<select name="date" onchange="this.form.submit()">

<?php
  for ($i = 0; $i <= 60; ++$i) {
    $time = strtotime(sprintf('+%d months', $i));
    $value = date('Y-m', $time);
    $label = date('F Y', $time);
    $nowvalue = date('Y-m');
    $nowlabel = date('F Y');
        if(isset($_GET['date'])) {
          if(strcmp($value,$_GET['date']) == 0) {
             //If 0, $value and $_GET['date'] are the same: The option is selected
             printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
             printf('<option value="%s">%s</option>', $value, $label);
          }
        } else {
          if($value == $nowvalue) {
            printf('<option value="%s" selected>%s</option>', $value, $label);
          } else {
            printf('<option value="%s">%s</option>', $value, $label);  
          }
    }
  }
  ?>
</select>
</form>

This outputs a select list of upcoming months, that onchange, reloads the page with a different query in the URL for the calendar on that page to react on.

If i manually update the query in the URL, it works fine, but this select list is repeating dates, have a look at the image below...

enter image description here

This cant be a coincidence that all of the months with the shortest days are missing, or in fact have been replaced with the same name as the month before?

Does anyone have an idea why this might be happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because when you loop through dates on a monthly basis on the 31st of the month you will come across months that have less than 30 days. PHP does automatically adjust the date to the last day of the month but instead goes to the end of the month and then adds the remaining days to it and gets the date that way which is the next month.

So if you get to February, which only has 28 days (most years) it will get to the 28th and add three days and give you March 3rd.

To solve this you need to set the date to the first day of the month and then iterate through the dates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...