在表單與報表開發中,日期時間的驗證、格式化與換算可說是家常便飯。本文分享一個把這些常用操作封裝起來的 TimeObjectUtil 工具類,讓你在各個專案間重複使用。
這個工具類遵循一個原則:所有違規的驗證一律回傳 false,讓呼叫端容易判斷。它涵蓋了毫秒與時間格式的雙向轉換、多種格式化輸出,以及各種時間區間的合理性驗證。
以下為格式化與比較的核心部分:
var TimeObjectUtil;
TimeObjectUtil = {
getCurrentMsTime : function() {
var myDate = new Date();
return myDate.getTime();
},
formatterDateTime : function(date) {
var datetime = date.getFullYear()
+ "-" + ((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1))
+ "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate())
+ " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours())
+ ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())
+ ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
return datetime;
},
compareDateEndTimeGTStartTime : function(startTime, endTime) {
return ((new Date(endTime.replace(/-/g, "/"))) > (new Date(startTime.replace(/-/g, "/"))));
}
/* ...其餘方法依此類推... */
};
把這些繁瑣又容易出錯的時間處理邏輯集中封裝成一個工具類,不僅讓主程式更乾淨,也大幅降低了重複撰寫與出錯的機率。各位可以依實際專案需求,增減或調整其中的方法。