查詢表單很常需要預設一段時間範圍,最典型的就是「近一個月」。做法是:結束時間設為現在,起始時間用 setMonth 往前推一個月,然後格式化填入欄位。
// 先擴充一個格式化方法
Date.prototype.format = function(format) {
var o = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"h+": this.getHours(), // 時
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
};
var begin = new Date();
var end = new Date();
// 往前推一個月
begin.setMonth(begin.getMonth() - 1);
var begintime = begin.format("yyyy-MM-dd");
var endtime = end.format("yyyy-MM-dd");
$('#txtBeginVisitTime').val(begintime);
$('#txtEndVisitTime').val(endtime);

一、setMonth 的結果沒有被使用。原寫法是 new Date(begin.setMonth(...)),但這行建立的新物件沒有指派給任何變數。還好 setMonth 是直接改動原物件,所以 begin 本身已經變了,結果勉強正確——但寫法容易誤導,直接 begin.setMonth(begin.getMonth() - 1) 就好。
二、大小寫不一致。定義的是 format,呼叫的卻是 Format,在區分大小寫的環境會直接報錯。
三、跨年會出錯。只減月份不處理年份時,一月往前推一個月會得到「去年 13 月」,被 Date 自動進位成隔年一月,結果對但邏輯不透明。
不必擴充 prototype,也不必自己寫格式化:
var end = new Date();
var begin = new Date();
begin.setMonth(begin.getMonth() - 1);
var fmt = function(d) {
return d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
};
$('#txtBeginVisitTime').val(fmt(begin));
$('#txtEndVisitTime').val(fmt(end));
月末會有陷阱。3 月 31 日往前推一個月,setMonth(1) 會變成 2 月 31 日,也就是 3 月 3 日——不是預期的 2 月底。若要嚴謹處理月末,建議引入 Day.js 或 date-fns,用 subtract(1, 'month') 這類 API,它們會自動收斂到當月最後一天。
不要修改 Date.prototype。這是全域污染,多人協作或引入第三方套件時容易衝突。把 format 寫成獨立函式,風險小得多。
最後,如果日期欄位使用的是 HTML5 的 <input type="date">,記得它的值必須是 YYYY-MM-DD 格式,上面的 fmt() 正好符合。