简体   繁体   中英

adding leading zero to dates in php

I am trying to add a 0 infront of dates 1 through 9 as the dates are listed in the dropdown menu. Here is my code, i thought using d would add leading zeros but doesn't seem to be working. I do not have much php experience so this is a longshot... thank you in advanced!

<?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>"; 

} 
?> 

If i understand you correctly, you need this:

$day = 1;    
echo str_pad($day, 2, 0, STR_PAD_LEFT);

You can replace:

ECHO INTVAL($currentMonth);

with:

printf("%02s", $currentMonth);
$day_with_leading_zeroes = sprintf("%02d", $day);

instead of:

ECHO ">$currentDay\n"; 

you can type:

echo ">".($currentDay<10 ? "0" : "").$currentDay."\n";
$date =4
$month = 6
$year = 2013

if want display above in this format. 04/06/2013

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

if want display above in this format. 14/12/2013

printf('%02d/%02d/%04d', $date, $month, $year);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM