微信小程序--年月日時(shí)分-自定義日期組件

image.png

1 在components 下創(chuàng)建文件夾 datePicker
2 datePicker.json 下 { "component": true} 定義為組件
3 在until 下 創(chuàng)建dataPicker.js

class BaseInfo {
  constructor() {
    this.newDate = new Date();
  }
  withData(param) {
    return parseInt(param) < 10 ? '0' + param : '' + param;
  }
  getLoopArray(start, end) {
    var start = start || 0;
    var end = end || 0;
    var array = [];
    for (var i = start; i <= end; i++) {
      array.push(this.withData(i));
    }
    return array;
  }
  formatArr(dateString) {
    return [...dateString.split(' ')[0].split('-'), ...dateString.split(' ')[1].split(':')]
    //return [...dateString.split(' ')[0].split('-')]
  }
  beforeDateArr(disYear) {
    /*
     * 處理前
     * 獲取當(dāng)前時(shí)間
     */
    let year = this.newDate.getFullYear() - (disYear || 0)
    let month = this.newDate.getMonth() + 1
    let day = this.newDate.getDate()
    let hour = this.newDate.getHours()
    let minute = this.newDate.getMinutes()
    return [year, month, day, hour, minute]
  }
  afterDateArr() {
    /*
     * 處理后
     * 獲取當(dāng)前時(shí)間
     */
    let year = this.withData(this.newDate.getFullYear())
    let mont = this.withData(this.newDate.getMonth() + 1)
    let date = this.withData(this.newDate.getDate())
    let hour = this.withData(this.newDate.getHours())
    let minu = this.withData(this.newDate.getMinutes())
    return [year, mont, date, hour, minu];
  }
}

// 實(shí)現(xiàn)
class dateTimePicker extends BaseInfo {
  constructor(startDate, endDate, defaultDate) {
    super();
    this.dateTimeArray = null
    this.dateTime = null
    this.startDate = super.formatArr(startDate); // 開始時(shí)間
    this.endDate = endDate ? super.formatArr(endDate) : super.afterDateArr(); // 結(jié)束時(shí)間
    this.defaultDate = defaultDate ? super.formatArr(defaultDate) : this.startDate;
  }
  setValue(obj) {
    for (let key in obj) {
      this[key] = obj[key]
    }
  }
  /* 獲取當(dāng)前切換選擇的日期值*/
  getCurDateInfo() {
    return this.dateTime && this.dateTimeArray ? {
      year: this.dateTimeArray[0][this.dateTime[0]],
      month: this.dateTimeArray[1][this.dateTime[1]],
      day: this.dateTimeArray[2][this.dateTime[2]],
      hour: this.dateTimeArray[3][this.dateTime[3]],
      second: this.dateTimeArray[4][this.dateTime[4]],
    } : {}
  }
  /* 獲取月數(shù)組*/
  getMonths() {
    let array = []
    const year = (this.getCurDateInfo().year || this.defaultDate[0]).replace(/年/, '');
    if (this.startDate[0] == this.endDate[0]) {
      /* 
       * 開始的年和結(jié)束的年相同
       * 就取(開始月腾仅,結(jié)束月)
       */
      array = super.getLoopArray(parseInt(this.startDate[1]), parseInt(this.endDate[1]))
    } else {
      switch (year) {
        case this.startDate[0]:
          /* 開始年 */
          array = super.getLoopArray(parseInt(this.startDate[1]), 12)
          break;
        case this.endDate[0]:
          /* 結(jié)束年 */
          array = super.getLoopArray(1, parseInt(this.endDate[1]))
          break;
        default:
          array = super.getLoopArray(1, 12)
          break;
      }
    }

    return array;
  }
  /* 獲取日數(shù)組*/
  getDays() {
    let array = []
    let lastDay = null
    const year = (this.getCurDateInfo().year || this.defaultDate[0]).replace(/年/, '');
    const month = (this.getCurDateInfo().month || this.defaultDate[1]).replace(/月/, '');
    const flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    switch (month) {
      case '01':
      case '03':
      case '05':
      case '07':
      case '08':
      case '10':
      case '12':
        lastDay = 31
        break;
      case '04':
      case '06':
      case '09':
      case '11':
        lastDay = 30
        break;
      case '02':
        lastDay = flag ? 29 : 28
        break;
      default:
        array = '月份格式不正確蹦魔,請(qǐng)重新輸入!'
    }
    const afterDateArr = super.afterDateArr()
    const _start = year == this.startDate[0] && month == this.startDate[1]
    const _end = year == this.endDate[0] && month == this.endDate[1]
    if (this.startDate[0] == this.endDate[0] && this.startDate[1] == this.endDate[1]) {
      /*
       * 開始的年和結(jié)束的年相同饲嗽,開始月和結(jié)束月相同
       * 就取(開始日粘舟,結(jié)束日)
       */
      array = super.getLoopArray(parseInt(this.startDate[2]), parseInt(this.endDate[2]))
    } else {
      if (_start) { // 開始年月
        array = super.getLoopArray(parseInt(this.startDate[2]), lastDay)
      } else if (_end) { // 結(jié)束年月
        array = super.getLoopArray(1, parseInt(this.endDate[2]))
      } else {
        array = super.getLoopArray(1, lastDay)
      }
    }

    return array;
  }

  /* 獲取小時(shí)數(shù)組*/
  getHours() {
    let array = []
    const year = (this.getCurDateInfo().year || this.defaultDate[0]).replace(/年/, '');
    const month = (this.getCurDateInfo().month || this.defaultDate[1]).replace(/月/, '');
    const day = (this.getCurDateInfo().day || this.defaultDate[2]).replace(/日/, '');
    const _start = year == this.startDate[0] && month == this.startDate[1] && day == this.startDate[2]
    const _end = year == this.endDate[0] && month == this.endDate[1] && day == this.endDate[2]
    const _equal = this.startDate[0] == this.endDate[0] && this.startDate[1] == this.endDate[1] && this.startDate[
      2] == this.endDate[2]
    if (_equal) {
      /*
       * 開始的年月日和結(jié)束的年月日都相同
       * 就取(開始小時(shí)凉驻,結(jié)束小時(shí))
       */
      array = super.getLoopArray(parseInt(this.startDate[3]), parseInt(this.endDate[3]))
    } else {
      if (_start) { // 開始年月日
        array = super.getLoopArray(parseInt(this.startDate[3]), 23)
      } else if (_end) { // 結(jié)尾年月日
        array = super.getLoopArray(0, parseInt(this.endDate[3]))
      } else {
        array = super.getLoopArray(0, 23)
      }
    }
    return array;
  }
  /* 獲取分鐘數(shù)組*/
  getMinutes(years, months, days, hours) {
    let array = []
    const year = (this.getCurDateInfo().year || this.defaultDate[0]).replace(/年/, '');
    const month = (this.getCurDateInfo().month || this.defaultDate[1]).replace(/月/, '');
    const day = (this.getCurDateInfo().day || this.defaultDate[2]).replace(/日/, '');
    const hour = (this.getCurDateInfo().hour || this.defaultDate[3]).replace(/時(shí)/, '');
    const _start = year == this.startDate[0] && month == this.startDate[1] && day == this.startDate[2] && hour == this
      .startDate[3]
    const _end = year == this.endDate[0] && month == this.endDate[1] && day == this.endDate[2] && hour == this
      .endDate[3]
    const _equal = this.startDate[0] == this.endDate[0] && this.startDate[1] == this.endDate[1] && this.startDate[
      2] == this.endDate[2] && this.startDate[3] == this.endDate[3]
    if (_equal) {
      /*
       * 開始的年月日時(shí)和結(jié)束的年月日時(shí)都相同
       * 就取(開始小時(shí)贝淤,結(jié)束小時(shí))
       */
      array = super.getLoopArray(parseInt(this.startDate[4]), parseInt(this.endDate[4]))
    } else {
      if (_start) { // 開始年月日
        array = super.getLoopArray(parseInt(this.startDate[4]), 59)
      } else if (_end) { // 結(jié)尾年月日
        array = super.getLoopArray(0, parseInt(this.endDate[4]))
      } else {
        array = super.getLoopArray(0, 59)
      }
    }
    return array;
  }
  /*  */
  dispatch(index) {
    let arr = []
    switch (index) {
      case 0:
        arr = super.getLoopArray(this.startDate[0], this.endDate[0]);
        break;
      case 1:
        arr = this.getMonths();
        break;
      case 2:
        arr = this.getDays();
        break;
      case 3:
        arr = this.getHours();
        break;
      case 4:
        arr = this.getMinutes();
        break;
      default:
        break;
    }
    return arr
  }

  /* 初始默認(rèn)數(shù)據(jù) */
  render() {
    const dateTime = []
    const dateTimeArray = [
      [],
      [],
      [],
      [],
      []
    ];
    /*年月日 時(shí)分秒*/
    for (let i = 0; i < dateTimeArray.length; i++) {
      dateTimeArray[i] = this.dispatch(i)
    }
    dateTimeArray.forEach((current, index) => {
      const _index = current.indexOf(this.defaultDate[index])
      dateTime.push(_index == -1 ? 0 : _index);
    });

    return {
      dateTimeArray,
      dateTime
    }
  }
}

function newDateTimePicker(startDateTime, endDateTime, pText) {
  let newDateTimePicker = new dateTimePicker(startDateTime, endDateTime, pText)
  return newDateTimePicker
}
module.exports = {
  newDateTimePicker: newDateTimePicker,
}
wxml--組件內(nèi)容
<picker class="dateTimePicker" mode="multiSelector" value="{{dateTime}}" bindchange="changeDateTime" bindcolumnchange="changeDateTimeColumn" range="{{dateTimeArray}}">
  <view class="tui-picker-detail wrap column-center">
    <text style="color:{{(dateTimeWhole||params.pText)?'#999999':'#999999'}}">{{dateTimeWhole || params.pText || params.placeholder ||"請(qǐng)選擇時(shí)間"}}</text>
    <!-- <image class="icon" src="/static/mine/meArrowRight.png" mode=""></image> -->
  </view>
</picker>
js--組件內(nèi)容
const App = getApp();
//引入時(shí)間插件
const dateTimePicker = require('../../utils/dataPicker.js')
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 組件的屬性列表
   */
  properties: {
    params: {
      type: Object,
      value: {
        placeholder: '請(qǐng)選擇時(shí)間',
        startDateTime: '',
        endDateTime: '',
        pText: ''
      }
    },
  },

  /**
   * 組件的初始數(shù)據(jù)
   */
  data: {
    dateTimeArray: null,
    dateTime: null,
    startDateTime: '',
    endDateTime: '',
    dateTimeWhole: '',
  },
  lifetimes: {
    attached: function () {
      this.setData({
        startDateTime: this.data.params.startDateTime,
        endDateTime: this.data.params.endDateTime
      })
      this.initData()
    }
  },
  pageLifetimes: {
    show: function () {
      this.setData({
        startDateTime: this.data.params.startDateTime,
        endDateTime: this.data.params.endDateTime
      })
      this.initData()
    },
    hide: function () {
      // 頁(yè)面被隱藏
    },
    resize: function (size) {
      // 頁(yè)面尺寸變化
    }
  },
  /**
   * 組件的方法列表
   */
  methods: {
    initData(date) {
      // 獲取完整的年月日 時(shí)分秒,以及默認(rèn)顯示的數(shù)組
      this.data.unit = ['年', '月', '日', '時(shí)', '分']
      this.data.dateTimePicker = dateTimePicker.newDateTimePicker(this.data.startDateTime, this.data.endDateTime, this.data.params.pText)
      let obj = this.data.dateTimePicker.render();
      let lastArray = obj.dateTimeArray;
      let lastTime = obj.dateTime;
      for (let i = 0; i < lastArray.length; i++) {
        lastArray[i] = lastArray[i].map(m => m + this.data.unit[i])
      }
      this.data.dateTimeArray = lastArray
      this.data.dateTime = lastTime
      this.setData({
        dateTimeArray: this.data.dateTimeArray,
        dateTime: this.data.dateTime
      })
    },
    changeDateTime(e) {
      this.data.dateTime = e.detail.value
      const year = this.data.dateTimeArray[0][this.data.dateTime[0]].replace(/年/, '')
      const month = this.data.dateTimeArray[1][this.data.dateTime[1]].replace(/月/, '')
      const day = this.data.dateTimeArray[2][this.data.dateTime[2]].replace(/日/, '')
      const hour = this.data.dateTimeArray[3][this.data.dateTime[3]].replace(/時(shí)/, '')
      const minute = this.data.dateTimeArray[4][this.data.dateTime[4]].replace(/分/, '')
      // this.data.dateTimeWhole = `${year}-${month}-${day} ${hour}:${minute}`
      this.data.dateTimeWhole = `${year}-${month}-${day} ${hour}:${minute}`
      this.setData({
        dateTimeWhole: this.data.dateTimeWhole,
      })
      console.log(this.data.dateTimeWhole)
      this.triggerEvent('getDateString', this.data.dateTimeWhole)
    },
    changeDateTimeColumn(e) {
      const {
        column,
        value
      } = e.detail
      // this.$set(this.data.dateTime, column, value)
      let dateTimeTemp = 'dateTime[' + column + ']'
      this.setData({
        [dateTimeTemp]: value
      })
      this.data.dateTimePicker.setValue({
        dateTimeArray: this.data.dateTimeArray,
        dateTime: this.data.dateTime
      })
      for (let i = 1; i < this.data.dateTime.length; i++) {
        if (column == i - 1) {
          for (let j = i; j < this.data.dateTime.length; j++) {
            // this.$set(this.data.dateTime, j, 0)
            let temp = 'dateTime[' + j + ']'
            this.setData({
              [temp]: 0
            })
          }
        }
        let arr = this.data.dateTimePicker.dispatch(i).map(m => m + this.data.unit[i])
        // this.$set(this.data.dateTimeArray, i, arr)
        let temp1 = 'dateTimeArray[' + i + ']'
        this.setData({
          [temp1]: arr
        })
      }
      this.setData({
        dateTimeArray: this.data.dateTimeArray,
        dateTime: this.data.dateTime
      })
    },


  }
})

//組件css
/* pages/components/datePicker/datePicker.wxss */
.dateTimePicker {
  text-align: left;
  width: 300rpx;
}

.tui-picker-detail {
  border-radius: 10rpx;

  font-size: 20rpx;
  /* width: 200rpx; */
  text-align: right;
}

.icon {
  width: 16rpx;
  height: 32rpx;
}

頁(yè)面應(yīng)用方法

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末郭计,一起剝皮案震驚了整個(gè)濱河市霸琴,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌昭伸,老刑警劉巖梧乘,帶你破解...
    沈念sama閱讀 207,248評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異庐杨,居然都是意外死亡选调,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門灵份,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)仁堪,“玉大人,你說(shuō)我怎么就攤上這事填渠∠夷簦” “怎么了?”我有些...
    開封第一講書人閱讀 153,443評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵氛什,是天一觀的道長(zhǎng)莺葫。 經(jīng)常有香客問(wèn)我,道長(zhǎng)枪眉,這世上最難降的妖魔是什么捺檬? 我笑而不...
    開封第一講書人閱讀 55,475評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮贸铜,結(jié)果婚禮上堡纬,老公的妹妹穿的比我還像新娘聂受。我一直安慰自己,他們只是感情好隐轩,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,458評(píng)論 5 374
  • 文/花漫 我一把揭開白布饺饭。 她就那樣靜靜地躺著渤早,像睡著了一般职车。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鹊杖,一...
    開封第一講書人閱讀 49,185評(píng)論 1 284
  • 那天悴灵,我揣著相機(jī)與錄音,去河邊找鬼骂蓖。 笑死积瞒,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的登下。 我是一名探鬼主播茫孔,決...
    沈念sama閱讀 38,451評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼被芳!你這毒婦竟也來(lái)了缰贝?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,112評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤畔濒,失蹤者是張志新(化名)和其女友劉穎剩晴,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體侵状,經(jīng)...
    沈念sama閱讀 43,609評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡赞弥,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,083評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了趣兄。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绽左。...
    茶點(diǎn)故事閱讀 38,163評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖艇潭,靈堂內(nèi)的尸體忽然破棺而出拼窥,到底是詐尸還是另有隱情,我是刑警寧澤暴区,帶...
    沈念sama閱讀 33,803評(píng)論 4 323
  • 正文 年R本政府宣布闯团,位于F島的核電站,受9級(jí)特大地震影響仙粱,放射性物質(zhì)發(fā)生泄漏房交。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,357評(píng)論 3 307
  • 文/蒙蒙 一伐割、第九天 我趴在偏房一處隱蔽的房頂上張望候味。 院中可真熱鬧刃唤,春花似錦、人聲如沸白群。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)帜慢。三九已至笼裳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間粱玲,已是汗流浹背躬柬。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留抽减,地道東北人允青。 一個(gè)月前我還...
    沈念sama閱讀 45,636評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像卵沉,于是被迫代替她去往敵國(guó)和親颠锉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,925評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容