摘要:最近做小程序開發(fā),出于練手,也是工作需要,就做了個微信小程序的類似于酒店預(yù)訂的日歷插件。計算每月第一天是星期幾日一二三四五六利用構(gòu)造函數(shù)生成數(shù)據(jù),一會用。
最近做小程序開發(fā),出于練手,也是工作需要,就做了個微信小程序的類似于酒店預(yù)訂的日歷插件。
先上圖;
這個插件分為上下兩部分,上邊是tab欄,會根據(jù)當(dāng)前的日期自動定位到當(dāng)前,并展示以后7天的日期,下邊為內(nèi)容展示,隨tab欄變化而變化。
思路:
首先用new Data()時間對象初始化時間,獲取當(dāng)前的日期,用new Date(Date.UTC(year, month - 1, 1)).getDay()獲取每個月的第一天是星期幾。
// 計算每月第一天是星期幾 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 = ["日", "一", "二", "三", "四", "五", "六"];
利用構(gòu)造函數(shù)生成數(shù)據(jù),一會用。
//利用構(gòu)造函數(shù)創(chuàng)建對象 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循環(huán)生成json數(shù)據(jù):
for(var i=1;i<=monthLength;i++){ //當(dāng)循環(huán)完一周后,初始化再次循環(huán) if(x>6){ x=0; } //利用構(gòu)造函數(shù)創(chuàng)建對象 that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0]) x++; }
這里因為一周有7天,所以當(dāng)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 = ["日", "一", "二", "三", "四", "五", "六"]; //利用構(gòu)造函數(shù)創(chuàng)建對象 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; } } //當(dāng)前月份的天數(shù) var monthLength= getThisMonthDays(cur_year, cur_month) //當(dāng)前月份的第一天是星期幾 var week = getFirstDayOfWeek(cur_year, cur_month) var x = week; for(var i=1;i<=monthLength;i++){ //當(dāng)循環(huán)完一周后,初始化再次循環(huán) if(x>6){ x=0; } //利用構(gòu)造函數(shù)創(chuàng)建對象 that.data.calendar[i] = new calendar(i, [weeks_ch[x]][0]) x++; } //限制要渲染的日歷數(shù)據(jù)天數(shù)為7天以內(nèi)(用戶體驗) var flag = that.data.calendar.splice(cur_date, that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length:7) that.setData({ calendar: flag }) //設(shè)置scroll-view的子容器的寬度 that.setData({ width: 186 * parseInt(that.data.calendar.length - cur_date <= 7 ? that.data.calendar.length : 7) })
插件地址:github地址
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/94609.html