在微信小程序或者web項(xiàng)目中經(jīng)常用到需要獲取當(dāng)前時(shí)間往后多少天并顯示日期含星期幾的需求,現(xiàn)在優(yōu)化為只調(diào)用一個(gè)js函數(shù),只需調(diào)用getDates(days)函數(shù),傳入需要顯示多少天日期,即返回一個(gè)攜帶日期的數(shù)組。
//獲取d當(dāng)前時(shí)間多少天后的日期和對(duì)應(yīng)星期
function getDates(days,todate=getCurrentMonthFirst()) {//todate默認(rèn)參數(shù)是當(dāng)前日期,可以傳入對(duì)應(yīng)時(shí)間
var dateArry = [];
for (var i = 0; i < days; i++) {
var dateObj = dateLater(todate, i);
dateArry.push(dateObj)
}
return dateArry;
}
/**
* 傳入時(shí)間后幾天
* param:傳入時(shí)間:dates:"2018-04-02",later:往后多少天
*/
function dateLater(dates, later) {
let dateObj = {};
let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
let date = new Date(dates);
date.setDate(date.getDate() + later);
let day = date.getDay();
dateObj.year = date.getFullYear();
dateObj.month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth()+1);
dateObj.day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
dateObj.week = show_day[day];
return dateObj;
}
//獲取當(dāng)前時(shí)間
function getCurrentMonthFirst() {
var date = new Date();
var todate = date.getFullYear() + "-" + ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth()+1) + "-" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
return todate;
}
微信小程序需要導(dǎo)出函數(shù),然后在需要的頁面引入使用即可。
module.exports = {
getDates: getDates
}
具體應(yīng)用實(shí)例請(qǐng)看github上面的日期選擇組件栗子:https://github.com/kingbuwu/weapp-date.git
如有幫助請(qǐng)點(diǎn)點(diǎn)喜歡,謝謝!