最近作小程序開發,出於練手,也是工做須要,就作了個微信小程序的相似於酒店預訂的日曆插件。
先上圖;
git
這個插件分爲上下兩部分,上邊是tab欄,會根據當前的日期自動定位到當前,並展現之後7天的日期,下邊爲內容展現,隨tab欄變化而變化。
思路:
首先用new Data()
時間對象初始化時間,獲取當前的日期,用new Date(Date.UTC(year, month - 1, 1)).getDay()
獲取每一個月的第一天是星期幾。github
// 計算每個月第一天是星期幾 function getFirstDayOfWeek(year, month) { return new Date(Date.UTC(year, month - 1, 1)).getDay(); } const date = new Date(); const cur_year = date.getFullYear(); const cur_month = date.getMonth() + 1; const cur_date=date.getDate(); const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
利用構造函數生成數據,一會用。json
//利用構造函數建立對象 function calendar(date,week){ this.date=cur_year+'-'+cur_month+'-'+date; if(date==cur_date){ this.week = "今天"; }else if(date==cur_date+1){ this.week = "明天"; }else{ this.week = '星期' + week; } }
使用for循環生成json數據:小程序
for(var i=1;i<=monthLength;i++){ //當循環完一週後,初始化再次循環 if(x>6){ x=0; } //利用構造函數建立對象 that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0]) x++; }
這裏由於一週有7天,因此當x>6的時候,重置爲0。
最後展現部分源碼微信小程序
var that=this; function getThisMonthDays(year, month) { return new Date(year, month, 0).getDate(); } // 計算每個月第一天是星期幾 function getFirstDayOfWeek(year, month) { return new Date(Date.UTC(year, month - 1, 1)).getDay(); } const date = new Date(); const cur_year = date.getFullYear(); const cur_month = date.getMonth() + 1; const cur_date=date.getDate(); const weeks_ch = ['日', '一', '二', '三', '四', '五', '六']; //利用構造函數建立對象 function calendar(date,week){ this.date=cur_year+'-'+cur_month+'-'+date; if(date==cur_date){ this.week = "今天"; }else if(date==cur_date+1){ this.week = "明天"; }else{ this.week = '星期' + week; } } //當前月份的天數 var monthLength= getThisMonthDays(cur_year, cur_month) //當前月份的第一天是星期幾 var week = getFirstDayOfWeek(cur_year, cur_month) var x = week; for(var i=1;i<=monthLength;i++){ //當循環完一週後,初始化再次循環 if(x>6){ x=0; } //利用構造函數建立對象 that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0]) x++; } //限制要渲染的日曆數據天數爲7天之內(用戶體驗) var flag = that.data.calendar.splice(cur_date, that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length:7) that.setData({ calendar: flag }) //設置scroll-view的子容器的寬度 that.setData({ width: 186 * parseInt(that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length : 7) })
插件地址:github地址微信