函數原型
{html_select_date
prefix="Date_"
start_year="-10"
end_year="+2"
field_order="MDY"
month_format="%B"
day_format="%02d"
display_days=true
display_months=true
display_years=true
year_as_text=false
reverse_years=false
year_size=0
month_size=0
day_size=0
}
核心參數詳解
| 參數 | 類型 | 默認值 | 說明 |
| prefix | string | "Date_" | 生成 select 的 name 前綴 |
| start_year | string | 當前年 | 起始年份,支援相對格式:"-10" 表示 10 年前 |
| end_year | string | 當前年 | 結束年份,支援相對格式:"+2" 表示 2 年後 |
| field_order | string | "MDY" | 字段順序:M=月、D=日、Y=年 |
| month_format | string | "%B" | 月份格式:%B=完整名、%b=縮寫、%m=數字 |
| day_format | string | "%02d" | 日期格式:%d=不補零、%02d=補零 |
| display_days | bool | true | 是否顯示日期下拉框 |
| display_months | bool | true | 是否顯示月份下拉框 |
| display_years | bool | true | 是否顯示年份下拉框 |
| year_as_text | bool | false | true=文本輸入框、false=下拉框 |
| reverse_years | bool | false | true=年份倒序(最新在前) |
| year_size | int | 0 | >1 顯示多行選擇框、0/1=下拉框 |
實際輸出示例
// 模板
{html_select_date prefix="StartDate" time=$time start_year="-5" end_year="+1" display_days=false}
// 輸出 (假設當前 2000 年 12 月)
關鍵限制與缺陷
- **日期與月份無關聯**:2 月仍顯示 31 日,需前端 JS 動態調整
- **無閏年處理**:無法自動調整 2 月天數
- **樣式定制困難**:生成的 HTML 結構固定,CSS 控制有限
- **無時區感知**:依賴服務器時間,非用戶本地時間
前端 JS 聯動補全方案
function updateDays(yearSelect, monthSelect, daySelect) {
const year = parseInt(yearSelect.value);
const month = parseInt(monthSelect.value);
let days = 31;
if ([4,6,9,11].includes(month)) days = 30;
else if (month === 2) {
days = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28;
}
daySelect.innerHTML = '';
for (let d = 1; d <= days; d++) {
const opt = document.createElement('option');
opt.value = d;
opt.textContent = d.toString().padStart(2, '0');
daySelect.appendChild(opt);
}
}
// 綁定事件
document.querySelector('[name="DateYear"]').addEventListener('change', () =>
updateDays(...document.querySelectorAll('[name="DateYear"], [name="DateMonth"], [name="DateDay"]'))
);
document.querySelector('[name="DateMonth"]').addEventListener('change', () =>
updateDays(...document.querySelectorAll('[name="DateYear"], [name="DateMonth"], [name="DateDay"]'))
);
現代替代方案
總結
`html_select_date()` 適合快速原型、後台管理等對體驗要求不高的場景。生產級項目建議採用前端日期選擇器組件,獲得更好的用戶體驗、驗證與本地化支援。若必須使用 Smarty,請務必配合 JS 實現「年-月-日」三級聯動。