我有一个php日历,它在页面上完美地显示了所有日期,但我需要将青少年日期显示为2位数字(01,02,03等),但它们没有显示出来 - 我怎么能这样做,因为它对结束链接很重要,即href =“events.php?date = 20131201”而不是href =“events.php?date = 2013121”。
这是我的完整代码,如果这会有所帮助:
<?php
$currDay = date("j");
$today = date("d"); // Current day
$month = date("m"); // Current month
$displaymonth = date("F");
$year = date("Y"); // Current year
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month
$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month
$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of current month
$laststart = $start - 1; // Days of previous month in calander
$counter = 1;
$nextMonthCounter = 1;
echo '
<div class="calendarHeader"><strong>'.$displaymonth.' '.$year.'</strong></div>
<div class="calendarDates">
<div class="calendarCell"><b>M</b></div>
<div class="calendarCell"><b>T</b></div>
<div class="calendarCell"><b>W</b></div>
<div class="calendarCell"><b>T</b></div>
<div class="calendarCell"><b>F</b></div>
<div class="calendarCell"><b>S</b></div>
<div class="calendarCell"><b>S</b></div>
<div class="clearLeft"></div>
</div>
<div class="calendar">
';
if($start > 5){ $rows = 6; }else {$rows = 5; }
for($i = 1; $i <= $rows; $i++){
for($x = 1; $x <= 7; $x++){
if((int)$currDay > (int)$date) {
$class ='calendarBlank';
}
if(($counter - $start) < 0){
$date = (($lastmonth - $laststart) + $counter);
$class = 'calendarBlank';
}else if(($counter - $start) >= $days){
$date = ($nextMonthCounter);
$nextMonthCounter++;
$class = 'calendarBlank';
}else if($counter <= $today){
$date = ($counter - $start + 1);
$class = 'calendarBlank';
}else{
$date = ($counter - $start + 1);
if($today == $counter - $start + 1){
$class = 'calendarToday';
}
}
echo '<a href="events.php?type='.$type.'&from='.$year,$month,$date.'&var='.$var.'" target="_parent"><div class="calendarCell '.$class.'">'.$date.'</div></a>';
$counter++;
$class = '';
}
}
echo '
<div class="clearLeft"></div>
</div>
';
?>
答案 0 :(得分:3)
您可以使用str_pad()
(假设我正确阅读您的代码,$date
是代表您日期的日期部分的变量)
$date = str_pad($date , 2, "0", STR_PAD_LEFT);
您也可以使用sprintf()
$date = sprintf("%02d", $date );
答案 1 :(得分:0)
$date = sprintf("%02d", $date); // e.g., 05
$date = sprintf("%4d%02d%02d", $year, $month, $day); // e.g., 20130704
答案 2 :(得分:0)
而不是'&from='.$year,$month,$date
使用
'&from='.sprintf("%04d%02d%02d", $year, $month, $date)
或
'&from='.$year.str_pad($month, 2, "0", STR_PAD_LEFT).str_pad($date, 2, "0", STR_PAD_LEFT)
或
'&from='.date("Ymd", mktime(0,0,0,$month,$date,$year))
答案 3 :(得分:0)
对于这种类型的日期操作,我强烈建议使用DateTime类:
$today = new DateTime("2013-01-01");
echo $today->format("Ymd");
// 20130101