在 EasyUI 中,datebox 控件初始化時自動顯示當前日期,且用戶不修改直接提交時也能獲取到當前時間值。
setValue 方法設置默認值;$(function(){
// 1. 獲取當前時間,格式需與 datebox 的 formatter 一致
var now = new Date();
var formatted = now.getFullYear() + '-' +
('0' + (now.getMonth()+1)).slice(-2) + '-' +
('0' + now.getDate()).slice(-2) + ' ' +
('0' + now.getHours()).slice(-2) + ':' +
('0' + now.getMinutes()).slice(-2);
// 2. 初始化 datebox 並設置值
$('#myDateBox').datebox({
formatter: function(date){
// 自定義格式化,與上方 formatted 保持一致
return date.getFullYear() + '-' + ...;
},
parser: function(s){
// 解析字符串為 Date 對象
if (!s) return new Date();
var ss = s.split(/[- :]/);
return new Date(ss[0], ss[1]-1, ss[2], ss[3]||0, ss[4]||0);
}
}).datebox('setValue', formatted);
});
formatter 和 parser 必須成對出現,保證顯示與解析一致;:ss;new Date() 取的是客戶端時間,如需服務端時間可通過 AJAX 獲取。