微信小程序獲取日期天數(shù)帶星期

在微信小程序或者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)喜歡,謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容