5

我正在尝试在日期 1 到 9 的前面添加 0,因为日期列在下拉菜单中。这是我的代码,我认为使用 d 会添加前导零,但似乎不起作用。我没有太多的 php 经验,所以这是一个远景......提前谢谢你!

<?PHP 

FUNCTION DateSelector($inName, $useDate=0) 
{ 
    /* create array so we can name months */ 
    $monthName = ARRAY(1=> "January", "February", "March", 
        "April", "May", "June", "July", "August", 
        "September", "October", "November", "December"); 

    /* if date invalid or not supplied, use current time */ 
    IF($useDate == 0) 
    { 
        $useDate = TIME(); 
    } 

    /* make month selector */ 
    ECHO "<SELECT NAME=" . $inName . "month>\n"; 
    FOR($currentMonth = 1; $currentMonth <= 12; $currentMonth++) 
    { 
        ECHO "<OPTION VALUE=\""; 
        ECHO INTVAL($currentMonth); 
        ECHO "\""; 
        IF(INTVAL(DATE( "m", $useDate))==$currentMonth) 
        { 
            ECHO " SELECTED"; 
        } 
        ECHO ">" . $monthName[$currentMonth] . "\n"; 
    } 
    ECHO "</SELECT>"; 

    /* make day selector */ 
    ECHO "<SELECT NAME=" . $inName . "day>\n"; 
    FOR($currentDay=1; $currentDay <= 31; $currentDay++) 
    { 
        ECHO "<OPTION VALUE=\"$currentDay\""; 
        IF(INTVAL(DATE( "d", $useDate))==$currentDay) 
        { 
            ECHO " SELECTED"; 
        } 
        ECHO ">$currentDay\n"; 
    } 
    ECHO "</SELECT>"; 

    /* make year selector */ 
    ECHO "<SELECT NAME=" . $inName . "year>\n"; 
    $startYear = DATE( "Y", $useDate); 
    FOR($currentYear = $startYear - 0; $currentYear <= $startYear+2;$currentYear++) 
    { 
        ECHO "<OPTION VALUE=\"$currentYear\""; 
        IF(DATE( "Y", $useDate)==$currentYear) 
        { 
            ECHO " SELECTED"; 
        } 
        ECHO ">$currentYear\n"; 
    } 
    ECHO "</SELECT>"; 

} 
?> 
4

5 回答 5

18

如果我理解正确,你需要这个:

$day = 1;    
echo str_pad($day, 2, 0, STR_PAD_LEFT);
于 2012-06-01T17:17:28.713 回答
2

您可以更换:

ECHO INTVAL($currentMonth);

和:

printf("%02s", $currentMonth);
于 2012-06-01T17:18:32.380 回答
2
$day_with_leading_zeroes = sprintf("%02d", $day);
于 2012-06-01T17:19:14.680 回答
0
$date =4
$month = 6
$year = 2013

如果想以这种格式显示在上面。2013 年 4 月 6 日

printf('%02d/%02d/%04d', $date, $month, $year);
$date =14
$month = 12
$year = 2013

如果想以这种格式显示在上面。2013 年 12 月 14 日

printf('%02d/%02d/%04d', $date, $month, $year);
于 2013-11-08T02:45:58.720 回答
0

代替:

ECHO ">$currentDay\n"; 

你可以输入:

echo ">".($currentDay<10 ? "0" : "").$currentDay."\n";
于 2012-06-01T17:24:37.910 回答