日期運算在前端很常見。以下範例先擴充 Date 的原型加入 format 方法,讓日期能格式化為 yyyy-MM-dd,再寫一個 getDate 函式推算相對日期。
<script type="text/javascript">
Date.prototype.format = function(fmt) {
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(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
(("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};
function getDate(day){
var zdate = new Date();
var sdate = zdate.getTime() - (1 * 24 * 60 * 60 * 1000);
var edate = new Date(sdate - (day * 24 * 60 * 60 * 1000)).format("yyyy-MM-dd");
return edate;
}
function wirte(){
document.write(getDate(-7));
}
</script>
用法對照:getDate(0) 為昨天、getDate(-1) 為今天、getDate(-7) 為七天後。原理是把毫秒數減去對應天數(一天 = 24×60×60×1000 毫秒),再交給 format Beautify 成易讀格式。