最近因爲數據庫的日誌查詢要做成按天分表來查詢,所以前端需要對日誌的查詢時間範圍限制在同一天內,而前端用來設置時間的是WdatePicker插件。比如下面的2個時間要設置爲同一天,百度了一下,發現了一篇文章,但是寫的模糊,沒有解決問題。後來看了幾篇其他關於WdatePicker插件的設定的文章,終於自己搞定了這個功能。現在把代碼貼出來,方便大家使用,也給博客增加點人氣,雖然是前端的知識,哈哈哈。
首先我們jsp頁面中代碼是這樣的。
<label>接收時間:</label>
<input name="params.starttime" value="" id="storageStartTime" onfocus="WdatePicker({ startDate: '%y-%M-01 00:00:00', dateFmt: 'yyyy-MM-dd HH:mm:ss',minDate:limitDayDate(1),maxDate:limitDayDate(2) })" class="Wdate" type="text" />
<label>到:</label>
<input name="params.endtime" value="" id="storageEndTime" onfocus="WdatePicker({ startDate: '%y-%M-01 00:00:00', dateFmt: 'yyyy-MM-dd HH:mm:ss', minDate:'#F{$dp.$D(\'storageStartTime\')}',maxDate:limitDayDate(3)})" class="Wdate" type="text" />
起始時間的標籤id是storageStartTime,而結束時間是storageEndTime。然後WdatePicker中的maxDate和minDate屬性就是分別規定時間最大值和最小值。關鍵在於limitDayDate(e)方法了。
//限制2個時間爲同一天
function limitDayDate(e) {
var dateString="";
if(e==2){//起始時間最大值判斷
var endDate = $dp.$("storageEndTime").value;
//var endDate = $("#storageEndTime").val();這樣取值也是可以的,上面無效的時候可以用普通的這種。
var limitDate = new Date();
if (endDate != ""&&endDate != null) {//當填有結束時間時,以結束時間爲最大值
var limitDate = new Date(endDate);
dateString = limitDate.getFullYear() + '-'
+ (limitDate.getMonth()+1) + '-'
+ limitDate.getDate()+' '
+ limitDate.getHours()+':'
+ limitDate.getMinutes()+':'
+limitDate.getSeconds();
}else{//結束時間空白時,不超出今天
dateString = limitDate.getFullYear() + '-'
+ (limitDate.getMonth()+1) + '-'
+ limitDate.getDate()+' '
+ '23:59:59';
}
}else if(e==1){//起始時間的最小值判斷
var endDate = $dp.$("storageEndTime").value;
var limitDate = new Date();
if (endDate != ""&&endDate != null) {//
var limitDate = new Date(endDate);
dateString = limitDate.getFullYear() + '-'
+ (limitDate.getMonth()+1) + '-'
+ limitDate.getDate()+' '+'00:00:00';
// + endDate.getHours()+':'
// + endDate.getMinutes()+':'
//+endDate.getSeconds();//
}
}else if(e==3){//結束時間最大值判斷
var limitDate = new Date();
var startDate = $dp.$("storageStartTime").value;
if(startDate!=""&&startDate!=null){//當有起始時間時,則以起始時間當天最後時間爲最大值
limitDate = new Date(startDate);
dateString = limitDate.getFullYear() + '-'
+ (limitDate.getMonth()+1) + '-'
+ limitDate.getDate()+' '
+ '23:59:59';
}else{//沒選擇起始時間時,默認是今天最大值
dateString = limitDate.getFullYear() + '-'
+ (limitDate.getMonth()+1) + '-'
+ limitDate.getDate()+' '
+ '23:59:59';
}
}
return dateString;
}
在這個方法中有3個分支。因爲需要控制起始時間和結束時間的最大值和最小值纔可以。而結束時間的最小值,那就是用戶設定好的起始時間。其中的邏輯相信仔細看過代碼就會明白了。其中getMonth()+1的原因在於月份存的是0到11。在這裏給讀者提個醒。應該沒什麼好描述的了。有問題歡迎留言~