How to get all days, months, and years in a drop d

2019-08-01 10:30发布

问题:

Is there a class or a php script that will echo in drop down fields all the days, months, and years. I need to use them for date of birth fields. I googled but nothing came up that i can implement or learn from. ANy ideas? thanks

回答1:

If you REALLY just want it done in PHP, here's a simple start:

<?php
    // lowest year wanted
    $cutoff = 1910;

    // current year
    $now = date('Y');

    // build years menu
    echo '<select name="year">' . PHP_EOL;
    for ($y=$now; $y>=$cutoff; $y--) {
        echo '  <option value="' . $y . '">' . $y . '</option>' . PHP_EOL;
    }
    echo '</select>' . PHP_EOL;

    // build months menu
    echo '<select name="month">' . PHP_EOL;
    for ($m=1; $m<=12; $m++) {
        echo '  <option value="' . $m . '">' . date('M', mktime(0,0,0,$m)) . '</option>' . PHP_EOL;
    }
    echo '</select>' . PHP_EOL;

    // build days menu
    echo '<select name="day">' . PHP_EOL;
    for ($d=1; $d<=31; $d++) {
        echo '  <option value="' . $d . '">' . $d . '</option>' . PHP_EOL;
    }
    echo '</select>' . PHP_EOL;
?>

Another method, similar output:
(Years will be in Ascending order, rather than Descending)

<?php
    $build = array(
        array('year', '1910', date('Y'), 'Y'),
        array('month', '1', '12', 'M'),
        array('day', '1', '31', 'j')
    );
    $doc = new DOMDocument();
    foreach ($build as $item) {
        $menu = $doc->createElement('select');
        $menu->setAttribute('name', $item[0]);
        for ($x=$item[1]; $x<=$item[2]; $x++) {
            $b = $item[3];
            $opt = $doc->createElement('option');
            $opt->setAttribute('value', $x);
            $opt->nodeValue = date($item[3], mktime(0,0,0,($b=='M'?$x:1),($b=='j'?$x:1),($b=='Y'?$x:1)));
            $menu->appendChild($opt);
        }
        $doc->appendChild($menu);
    }
    echo $doc->saveHTML();
?>


回答2:

Instead of going with three distinct <select>, which is not a very user-friendly solution, why not use some Javascript-based calendar widget ?


For example, I've heard about jQuery Datepicker quite a few times -- the effect is far better, don't you think :

        http://extern.pascal-martin.fr/so/5463037.png

(And that's just a screenshot of the demo on the page I linked to ; there are several options you can tune)



回答3:

The topic is old, but would say in the accepted answer to be added

date('M', mktime(0,0,0,$m))

-->

date('M', mktime(0,0,0,$m,1))

because on 29th, 30th and 31st the labels would be wrong. PHP takes as default the current day and will return wrong months in which this day is missing. PHP will interprete it as the month + 1 day and will show the following month



回答4:

I know that this is an old question but maybe this would help.

var_dump(cal_info(CAL_GREGORIAN )['months']);

http://php.net/manual/en/function.cal-info.php

http://php.net/manual/en/ref.calendar.php



标签: php calendar