实现微信小程序日期时间控件dateTimepicker

这是这篇文章的扩展
小程序实现日期时间控件picker - 菜工 - 博客园

 主要是实现了微信timepicker 的相同属性接口实现微信小程序日期时间控件dateTimepicker_第1张图片

 以下就是代码了

注意:这个可能是有问题的。如果是有问题。希望能及时反馈,把它完善好

index.wxml


  

index.js

const leftPad0 = function (v, n) {
  if (!v) {
    v = "";
  }
  let prefix = "";
  for (let i = 0; i < n; i++) {
    prefix += "0";
  }
  return (prefix + v).substr(-n);
};

const stringToDate = function (str) {
  if (str) {
    str = str.replace(/-/g, "/");
    let r = new Date(str);
    if (r == 'Invalid Date') {
      console.error('Invalid Date,value格式不对(yyyy-MM-dd hh:mm:ss)')
      return new Date();
    }
    return r
  }
  return new Date();
};

const isLeapYear = function (year) {
  if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {
    return true;
  }
  return false;
};
const now = new Date();
const formatAndCompute = function (date = now, num = 0) {
  //author: meizz   
  var fmt = 'yyyy-MM-dd hh:mm:ss'
  var o = {
    "M+": date.getMonth() + 1, //月份   
    "d+": date.getDate(), //日   
    "h+": date.getHours(), //小时   
    "m+": date.getMinutes(), //分   
    "s+": date.getSeconds() //秒         
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + num + '').substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
let beginYear = 1900;
const months = [];
for (var i = 0; i < 12; i++) {
  months.push(leftPad0(i + 1, 2) + "月");
}
const days = [];
for (var i = 0; i < 31; i++) {
  days.push(leftPad0(i + 1, 2) + "日");
}
const hours = [];
for (var i = 0; i < 24; i++) {
  hours.push(leftPad0(i, 2) + "时");
}
const minutes = [];
for (var i = 0; i < 60; i++) {
  minutes.push(leftPad0(i, 2) + "分");
}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    value: String,
    value: formatAndCompute(),
    observer: function (newVal, oldVal) {
      this.setData({
        valueArray: this._dateToValueArray(stringToDate(newVal)),
      })
    },
    start: {
      type: String,
      value: formatAndCompute(undefined, -2),
      observer: function (newVal, oldVal) {
        this.initYearsArr();
      }
    },
    end: {
      type: String,
      value: formatAndCompute(undefined, 2),
      observer: function (newVal, oldVal) {
        this.initYearsArr();
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    valueArray: [0, 0, 0, 0, 0],
    startArray: [0, 0, 0, 0, 0],
    endArray: [0, 0, 0, 0, 0],
    rangeValues: [
      [],
      months,
      days,
      hours,
      minutes
    ],
    isFirst: true,
    pickerYear: beginYear,
    pickerMonth: 1
  },
  ready() {
    this.initYearsArr('init');
  },
  observers: {},
  /**
   * 组件的方法列表
   */
  methods: {
    initYearsArr(f) {
      if (f != 'init' && this.data.isFirst) {
        return;
      }
      this.data.isFirst = false;
      let sy = Number(this.data.start.substr(0, 4));
      let ey = Number(this.data.end.substr(0, 4));
      beginYear = sy
      let years = [];
      for (var i = sy; i <= ey; i++) {
        years.push(i + "年");
      }
      this.data.rangeValues[0] = years;
      this.setData({
        rangeValues: this.data.rangeValues,
        valueArray: this._dateToValueArray(stringToDate(this.data.value)),
        startArray: this._dateToValueArray(stringToDate(this.data.start)),
        endArray: this._dateToValueArray(stringToDate(this.data.end)),
      })
    },
    _dateToValueArray(date) {
      return [date.getFullYear() - beginYear, date.getMonth(), date.getDate() - 1, date.getHours(), date.getMinutes()];
    },
    _settMonthDays(year, month) {
      let monthDays = 31;
      switch (month) {
        case 2:
          monthDays = 28;
          if (isLeapYear(year)) {
            monthDays = 29;
          }
          break;
        case 4:
        case 6:
        case 9:
        case 11:
          monthDays = 30;
          break;
      }
      let days = [];
      for (let i = 0; i < monthDays; i++) {
        days.push(leftPad0(i + 1, 2) + "日");
      }
      this.setData({
        pickerYear: year,
        pickerMonth: month,
        "rangeValues[2]": days
      });
    },
    handleCancel(e) {
      this.setData({
        valueArray: this.data.valueArray
      })
    },
    handleColumnChange(e) {
      let {
        column,
        value
      } = e.detail;
      this.data.valueArray[column] = value;
      if (this.comparenTwoArray(this.data.valueArray, this.data.startArray) == -1) {
        this.setData({
          valueArray: JSON.parse(JSON.stringify(this.data.startArray))
        })
      }
      if (this.comparenTwoArray(this.data.endArray, this.data.valueArray) == -1) {
        this.setData({
          valueArray: JSON.parse(JSON.stringify(this.data.endArray))
        })
      }
      if (e.detail.column > 1) return false;
      let year = this.data.pickerYear;
      let month = this.data.pickerMonth;
      if (e.detail.column == 0) {
        year = e.detail.value + beginYear;
      } else if (e.detail.column == 1) {
        month = e.detail.value + 1;
      }
      this._settMonthDays(year, month);
    },
    comparenTwoArray(a, b) {
      let i = 0,
        j = 0,
        aLen = a.length,
        bLen = b.length;
      while (i < aLen && j < bLen) {
        if (a[i] == b[j]) {
          i++;
          j++;
        } else {
          return a[i] > b[j] ? 1 : -1;
        }
      }
      if (i == aLen && j == bLen) {
        return 0;
      } else {
        return i == aLen ? -1 : 1;
      }
    },
    handleValueChange(e) {
      let dateArr = [];
      for (let i in e.detail.value) {
        let v = this.data.rangeValues[i][e.detail.value[i]];
        dateArr.push(v.toString().substr(0, v.length - 1))
      }
      let dateString = dateArr[0] + "-" + dateArr[1] + "-" + dateArr[2] + " " + dateArr[3] + ":" + dateArr[4] + ":00";
      this.triggerEvent('change', {
        date: stringToDate(dateString),
        value: dateString
      })
    }
  }
})

index.json

{
   "component": true,
   "usingComponents": {}
}

你可能感兴趣的:(微信小程序,微信小程序,小程序)