Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...