用最笨的方法記錄工作中的一次數據處理
最近在做移動端的一個項目,項目中涉及到了一個日期選擇的功能,如圖所示,看上去貌似很簡單,但是在做的過程中,發現難點主要是對于數據的組裝。項目中用到的是Vant組件庫,雖然其也有DatetimePicker時間選擇器,但是我看了好久感覺還是有點不符合UI設計,尤其是到某一天的時候還要展示其是周幾,很不好弄。所以想了想還是自己搞吧,借助Vant的Picker選擇器,自己寫了一個,最終的結果如圖2,還有點差別,但是那已經不是什么大問題了,很簡單!

UI稿

圖2
第一步:確定數據結構
Vant的Picker選擇器要求這種形式展現的數據結構是數組對象形式的,因此先確定了下面的這種數據結
[ { text: '2022年', type: 'year', shortName: 2022, children: [ { text: '01月', type: 'month', shortName: '1', children: [ { text: '01日(周一)', type: 'day', shortName: '1' } ] } ] } ];
第二步:處理數據
確定完數據結構后,然后就開始寫代碼了,具體的代碼如const nowDate = new Date(); // 獲取當前的日期const year = nowDate.getFullYear(); // 獲取當前的年份const month = []; // 存儲月份
for (let i = 1; i < 13; i++) { // 生成月份 month.push({ text: i < 10 ? '0' + `${i}月` : `${i}月` + '', type: 'month', shortName: i + '', children: dealDay(i) }); } // 處理日期(天和星期),因為每一年每個月份日期都是確定的(除2月外),所以大月是31天,小月是30天 function dealDay(month) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return dealDayWeek(year, month, 32); // 大月31 case 4: case 6: case 9: case 11: return dealDayWeek(year, month, 31); // 小月30 case 2: // 二月單獨處理 return dealMonthDay(year); } } // 判斷是閏年還是平年(閏年2月29,平年28) function dealMonthDay(year) { if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { return dealDayWeek(year, 2, 30); } else { return dealDayWeek(year, 2, 29); } } // 根據日期獲取星期幾
year: 年份
month: 月份
total: 每個月的總天數
function dealDayWeek(year, month, total) { const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; const days = []; for (let i = 1; i < total; i++) {
// 根據傳過來的每個月的天數循環和年、月組成新的數據,通過new Date('xxxx-xx-xx').getDay()的形式獲取到星期幾所對應的索引號,比如是0,則是星期天
const d = new Date(year + '-' + (month < 10 ? '0' + month : month) + '-' + (i < 10 ? '0' + i : i)).getDay();
const day = weeks[d]; // 獲取星期幾 days.push({ text: i < 10 ? '0' + i + `(${day})` : i + '' + `(${day})`, shortName: i + '', type: 'day' }); } // console.log(days) return days; }
// 組裝完的結果
let dateTime = [{
text: year + '年',
shortName: nowDate.getFullYear() + '',
type: 'year',
children: month
}]
console.log(dateTime)
最終得到的結果如圖片所示,大功告成(再繼續優化一下就ok了)


浙公網安備 33010602011771號