該組件是基於bootstrap的datetimepicker插件,所以在使用前先引入bootstrap.min.js和bootstrap.min.css,同時引入bootstrap-datetimepicker.min.js和bootstrap-datetimepicker.min.css。
另外,為了讓顯示的日期為中文需要引入bootstrap-datetimepicker.fr.js或者bootstrap-datepicker.zh-CN.js文件,需要在設置的時候,把language設為“zh-CN”(datetime.js)。
代碼片段:
--------------html----------------------
<div class="selectTime"> <span>選擇時間:</span> <input id="starttime" type="text" class="form-control width200" placeholder="請選擇開始時間" value="" > <input id="endtime" type="text" class="form-control width200" placeholder="請選擇結束時間" value="" > </div>
--------------js----------------------
//初始化時間組件
//$(function(){ } 是 $(document).ready(function(){...})的簡寫形式
$(function(){ $("#starttime").datetimepicker({ format: 'yyyy/mm/dd',//顯示格式 startView:2, minView:2, maxView :2, language: 'zh-CN', autoclose: 1,//選擇后自動關閉 clearBtn:true,//清除按鈕 initialDate : initDate(), //初始時間 }); $("#endtime").datetimepicker({ format: 'yyyy/mm/dd',//顯示格式 startView:2, minView:2, maxView :2, language: 'zh-CN', autoclose: 1,//選擇后自動關閉 clearBtn:true,//清除按鈕 initialDate : initDate(), //初始時間 }); }); //組件初始時間為當月一號 function initDate(){ var myDate = new Date(); var tYear = myDate.getFullYear() var tMonth = myDate.getMonth()+1 if(tMonth < 10){ tMonth = "0" + tMonth } var currentDate = tYear + "/" + tMonth + "/01" return currentDate }
另外附上屬性:
1)format
這個是必須要設置的。
默認值: 'mm/dd/yyyy'
日期格式, p, P, h, hh, i, ii, s, ss, d, dd, m, mm, M, MM, yy, yyyy 的任意組合。
2)weekStart
默認值:0。一周從哪一天開始。0(星期日)到6(星期六)
3)startDate
Date。默認值:開始時間
4)endDate
Date。默認值:結束時間
5)daysOfWeekDisabled 一周禁用的日期
String,Array。 默認值: '', []
6)autoclose
Boolean。 默認值:false
當選擇一個日期之后是否立即關閉此日期時間選擇器。
7)startView
Number, String。默認值:2, 'month'。
日期時間選擇器打開之后首先顯示的視圖。
- 0 or 'hour' for the hour view
- 1 or 'day' for the day view
- 2 or 'month' for month view (the default)
- 3 or 'year' for the 12-month overview
- 4 or 'decade' for the 10-year overview. Useful for date-of-birth datetimepickers.
8)minView
Number,String. 默認值:0, 'hour'。
日期時間選擇器所能夠提供的最精確的時間選擇視圖。
9)maxView
Number, String。 默認值:4, 'decade'
日期時間選擇器最高能展示的選擇范圍視圖。
10)language
String。默認值: 'en'
11)initDate
設置初始時間
另外附上其他屬性和方法鏈接:https://www.bootcss.com/p/bootstrap-datetimepicker/index.htm