我正在尝试添加日期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>";
}
?>
答案 0 :(得分:14)
如果我理解正确,你需要这个:
$day = 1;
echo str_pad($day, 2, 0, STR_PAD_LEFT);
答案 1 :(得分:2)
您可以替换:
ECHO INTVAL($currentMonth);
使用:
printf("%02s", $currentMonth);
答案 2 :(得分:1)
$day_with_leading_zeroes = sprintf("%02d", $day);
答案 3 :(得分:0)
而不是:
ECHO ">$currentDay\n";
你可以输入:
echo ">".($currentDay<10 ? "0" : "").$currentDay."\n";
答案 4 :(得分:0)
$date =4
$month = 6
$year = 2013
如果要以此格式显示上方。 2013年4月6日
printf('%02d/%02d/%04d', $date, $month, $year);
$date =14
$month = 12
$year = 2013
如果要以此格式显示上方。 14/12/2013
printf('%02d/%02d/%04d', $date, $month, $year);