Detailed explanation of how to use the Vue date time picker component

Detailed explanation of how to use the Vue date time picker component

This article example shares the specific code of the Vue date time picker component for your reference. The specific content is as follows

1. The effect diagram is as follows

Single-select date picker

Multi-select date picker

Date time picker

2. Preparation

Date prototype formatting tool method

Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //Month"d+": this.getDate(), //Day"h+": this.getHours(), //Hours"m+": this.getMinutes(), //Minutes"s+": this.getSeconds(), //Seconds"q+": Math.floor((this.getMonth() + 3) / 3), //QuarterS: this.getMilliseconds() //Milliseconds};
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").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;
};

Parse the month according to the input time and date, get the timestamps of the first and last day of the month, and the week corresponding to the timestamp of the month [Note]

  • Be sure to parse the 00:00 of the first day of the month. Most dates in js are parsed as 8:00 of that day, but some dates are parsed as 00:00 of that day, which will cause a timestamp error and result in an error in getting the number of days in the month.
  • Because the month usually contains some dates in the previous month or next month, it is also necessary to calculate the number of days in the week included in the month.
getMonthDay() {
  //The first day of the month var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();
//The first day of the next month minus 1s is the last day of the month this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }
//Calculate the number of weeks in the month and get the first day of the corresponding week var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
//Get the corresponding days of the month this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
},

3. Specific implementation

SCSS Styles

 .date-picker-bg {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
}

.date-picker {
  background-color: white;
  position: fixed;
  display: block;
  padding: 4px;
  z-index: 6;
  border: solid 1px gainsboro;
  border-radius: 2px;
  .picker-top {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    line-height: 30px;
    .picker-arrow {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width:30px;
      height: 30px;
      cursor: pointer;
      .iconfont {
        color: #8a8a8a;
      }
      .iconfont:active,
      .iconfont:hover {
        color: #388dea;
      }
    }

    .date-text {
      flex: 1;
      font-weight: bold;
      display: inline-block;
      text-align: center;
      font-size: 14px;
    }
  }

  .picker-content {
    display: block;
    border-top: solid 1px gainsboro;
    border-bottom: solid 1px gainsboro;
    height: 160px;
    table {
      width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      font-size: 12px;
      line-height: 20px !important;
      thead > tr {
        background-color: #cedeee;
        th {
          text-align: center;
          font-weight: normal;
        }
      }
      tbody {
        tr {
          td {
            font-weight: 600;
            cursor: pointer;
            text-align: center;
          }
          td.gray {
            font-weight: normal;
            color: #8a8a8a;
          }
          td.active {
            color: white;
            background: #388dea;
          }
        }
      }
    }
  }

  .picker-content1 {
    @extend .picker-content;
    display: flex;
    flex-direction: row;
    table {
      width: calc(100% - 40px);
    }
    .hour-list {
      display: inline-block;
      list-style: none;
      padding: 0;
      margin: 0;
      height: 100%;
      overflow-x:hidden;
      width: 40px;
      font-size:12px;

      overflow-y: auto;
      li {
        padding: 0;
        margin: 0;
        display: flex;
        align-items: center;
        padding: 0 4px;
        height:20px;
        cursor: pointer;
      }
      li:not(:last-child) {
        border-bottom: solid 1px gainsboro;
      }
      li.active {
        color: white;
        background: #388dea;
      }
    }
    .hour-list::-webkit-scrollbar {
      background: transparent;
      height: 8px;
      width:8px;
      border: none;
    }

    .hour-list::-webkit-scrollbar-thumb {
      background: lightgray;
      border-radius:5px;
    }
    //Set the scroll bar end
  }

  .picker-footer {
    display: block;
   line-height: 30px;
   text-align: right;
   white-space: nowrap;
    button {
      outline: none;
      border: solid 1px gainsboro;
      border-radius: 2px;
      color: #8a8a8a;
      height: 24px;
      font-size: 12px;
      background-color: #f3f3f3;
    }
    button:active,
    button:hover {
      border-color: #388dea;
      color: #388dea;
      background-color: #d9edf6;
    }
  }
}

Single-select date picker DatePicker

 <template>
  <div style="display:inline-block">
    <span @click="showPicker">{{getLangText(label.datePicker)}}</span>
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div
      class="date-picker"
      v-show="isShow"
      :style="{width:'220px',top:pickerTop>0?pickerTop+'px':''}"
    >
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo; &lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text">{{year}}-{{month>9?month:"0"+month}}</span>
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
        <!--Generate the corresponding month and week table start-->
      <div class="picker-content">
        <table>
          <thead>
            <tr>
              <th v-for="(item,idx) in weekList" :key="'week'+idx">{{getLangText(item)}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="idx ​​in weekNum" :key="'weekNum'+idx">
              <td
                v-for="m in 7"
                :key="'monthDay'+idx+'_'+m"
                :class="[new Date(monthList[idx-1][m-1]).getMonth()+1==month?'':'gray',selectDate==monthList[idx-1][m-1]?'active':'']"
                @click="onSelectDate(monthList[idx-1][m-1])"
                @dblclick="onConfirmDate(monthList[idx-1][m-1])"
              >{{new Date(monthList[idx-1][m-1]).getDate()}}</td>
              <!--Date is dark if it is the month, otherwise it is light-->
            </tr>
          </tbody>
        </table>
      </div>
        <!--Generate the corresponding month and week table end-->
      <div class="picker-footer">
        <button @click="closePicker">{{getLangText(label.close)}}</button>
        <button @click="setNow">{{getLangText(label.today)}}</button>
        <!-- <button @click="confirmPicker">{{getLangText(label.ok)}}</button> -->
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //Month"d+": this.getDate(), //Day"h+": this.getHours(), //Hours"m+": this.getMinutes(), //Minutes"s+": this.getSeconds(), //Seconds"q+": Math.floor((this.getMonth() + 3) / 3), //QuarterS: this.getMilliseconds() //Milliseconds};
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").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;
};
export default {
  name: "DatePicker",
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem("langType")
    },
    date: {
      type: String,
      default: new Date().format("yyyy-MM-dd")
    },
    isScroll: {
      type: Boolean,
      default: false
    },
     isShow:{
      type:Boolean,
      default:false
    }
  },
  data: () => ({
    label: {
      ok: { zh: "OK", en: "OK" },
      close: { zh: "Close", en: "close" },
      today: { zh: "today", en: "today" },
      datePicker: { zh: "Date Selection", en: "DatePicker" }
    },
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "Mon", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),

    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    pickerTop: 0
  }),
  watch:
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    }
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    showPicker(e) {
      if (this.isScroll) {
        this.pickerTop = e.clientY + e.offsetY;
        var h = document.getElementById("app").offsetHeight;
        if (this.pickerTop > h - 230) {
          this.pickerTop = h - 230;
        }
      }

       this.$emit("update:is-show",true);
      var time = new Date(this.date).getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show",false);
    },
    setNow() {
      this.year = new Date().getFullYear();
      this.month = new Date().getMonth() + 1;
      this.day = new Date().getDate();
      this.selectDate = new Date(
        new Date().format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    confirmPicker() {
      this.$emit("update:date", new Date(this.selectDate).format("yyyy-MM-dd"));
      this.$emit(
        "picker-result",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectDate(time) {
      this.selectDate = time;
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.$emit("update:date", new Date(time).format("yyyy-MM-dd"));
    }
  },
  mounted() {
    this.getMonthDay();
  }
};
</script>
<style lang="scss" scoped>
</style>

Multi-select date picker DatePicker1

<template>
  <div style="display:inline-block">
    <span @click="showPicker">Date Selection</span>
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div class="date-picker" v-show="isShow" style="width:220px">
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo; &lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text">{{year}}-{{month>9?month:"0"+month}}</span>
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
      <!--Generate the corresponding month and week table start-->
      <div class="picker-content">
        <table>
          <thead>
            <tr>
              <th v-for="(item,idx) in weekList" :key="'week'+idx">{{getLangText(item)}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="idx ​​in weekNum" :key="'weekNum'+idx">
              <td
                v-for="m in 7"
                :key="'monthDay'+idx+'_'+m"
                :class="[new Date(monthList[idx-1][m-1]).getMonth()+1==month?'':'gray',getSelectDate(monthList[idx-1][m-1])?'active':'']"
                @click="onSelectDate(monthList[idx-1][m-1])"
              >{{new Date(monthList[idx-1][m-1]).getDate()}}</td>
               <!--Date is dark if it is the month, otherwise it is light-->
            </tr>
          </tbody>
        </table>
      </div>
       <!--Generate the corresponding month and week table end-->
      <div class="picker-footer">
        <button @click="onFullMonth">Full Month</button>
        <button @click="onSelectDate(new Date(new Date().format('yyyy-MM-dd 00:00')).getTime())">Today</button>
        <button @click="closePicker">Close</button>
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //Month"d+": this.getDate(), //Day"h+": this.getHours(), //Hours"m+": this.getMinutes(), //Minutes"s+": this.getSeconds(), //Seconds"q+": Math.floor((this.getMonth() + 3) / 3), //QuarterS: this.getMilliseconds() //Milliseconds};
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").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;
};
export default {
  name: "DatePicker",
  props: {
    langType: {
      type: String,
      default: "zh"
    },
    date: {
      type: String,
      default: ""
    },

    isShow:{
      type:Boolean,
      default:false
    }
  },
  data: () => ({
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "Mon", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),

    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    result: []
  }),
  watch:
    date() {
      this.parseDate();
    },
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    }
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    getSelectDate(time) {
      for (var i = 0; i < this.result.length; i++) {
        if (time == this.result[i]) {
          return true;
        }
      }
      return false;
    },
    showPicker(e) {
      this.$emit("update:is-show",true);
      var time = new Date().getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show",false);
    },
    setNow() {
      this.year = new Date().getFullYear();
      this.month = new Date().getMonth() + 1;
      this.day = new Date().getDate();
      this.selectDate = new Date(
        new Date().format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    confirmPicker() {
      this.$emit("update:date", new Date(this.selectDate).format("yyyy-MM-dd"));
      this.$emit(
        "picker-result",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectDate(time) {
      this.selectDate = time;
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      var tag = true;
      //Cancel the selection if it is already selected for (var i = 0; i < this.result.length; i++) {
        if (this.result[i] == time) {
          tag = false;
          this.result.splice(i, 1);
          break;
        }
      }
      //Add date if not selected if (tag) {
        this.result.push(time);
        this.result = this.result.sort(function(a, b) {
          return a - b;
        });
      }
      var list = [];
      for (var i = 0; i < this.result.length; i++) {
        if (this.result[i] > 0) {
          list.push(new Date(this.result[i]).format("yyyy-MM-dd"));
        }
      }
      if (list.length > 0) {
        this.$emit("update:date", list.join(",") + "(total" + list.length + "days)");
      } else {
        this.$emit("update:date", "");
      }

      this.$emit("picker-result", this.result);
    },
    onFullMonth() {
      this.$emit("update:date", this.year + "year" + this.month + "month");
      this.$emit("picker-result", 30);
    },

    parseDate() {
      if (this.date) {
        var str = this.date;
        if (this.date.indexOf("(") > 0) {
          str = this.date.substring(0, this.date.indexOf("("));
        }
        if (str) {
          var list = str.split(",");
          var result = [];
          for (var i = 0; i < list.length; i++) {
            result.push(
              new Date(
                new Date(list[i]).format("yyyy-MM-dd 00:00:00")
              ).getTime()
            );
          }
          this.result = result;
        }
      }
    }
  },
  mounted() {
    this.getMonthDay();
    this.parseDate();
  }
};
</script>
<style lang="scss" scoped>
</style>

Date time picker

<template>
  <div style="display:inline-block">
    <span @click="showPicker">{{getLangText(label.datetimePicker)}}</span>
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div class="date-picker" v-show="isShow" style=" width: 260px;">
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo; &lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text">{{year}}-{{month>9?month:"0"+month}}</span>
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
      <div class="picker-content1">
        <table>
          <thead>
            <tr>
              <th v-for="(item,idx) in weekList" :key="'week'+idx">{{getLangText(item)}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="idx ​​in weekNum" :key="'weekNum'+idx">
              <td
                v-for="m in 7"
                :key="'monthDay'+idx+'_'+m"
                :class="[new Date(monthList[idx-1][m-1]).getMonth()+1==month?'':'gray',selectDate==monthList[idx-1][m-1]?'active':'']"
                @click="onSelectDate(monthList[idx-1][m-1])"
                @dblclick="onConfirmDate(monthList[idx-1][m-1])"
              >{{new Date(monthList[idx-1][m-1]).getDate()}}</td>
            </tr>
          </tbody>
        </table>
        <ul class="hour-list">
          <li
            v-for="n in 24"
            :key="'hourList'+n"
            @click="onSelectHour(n-1)"
            :class="[selectHour==n-1?'active':'']"
            @dblclick="onConfirmHour(n-1)"
          >{{n-1}}:00</li>
        </ul>
      </div>
      <div class="picker-footer">
        <button @click="closePicker">{{getLangText(label.close)}}</button>
        <button @click="setNow">{{getLangText(label.today)}}</button>
        <!-- <button @click="confirmPicker">{{getLangText(label.ok)}}</button> -->
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //Month"d+": this.getDate(), //Day"h+": this.getHours(), //Hours"m+": this.getMinutes(), //Minutes"s+": this.getSeconds(), //Seconds"q+": Math.floor((this.getMonth() + 3) / 3), //QuarterS: this.getMilliseconds() //Milliseconds};
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").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;
};
export default {
  name: "DateTimePicker",
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem("langType")
    },
    datetime: {
      type: String,
      default: new Date().format("yyyy-MM-dd hh:00")
    },
     isShow:{
      type:Boolean,
      default:false
    }
  },
  data: () => ({

    label: {
      ok: { zh: "OK", en: "OK" },
      close: { zh: "Close", en: "close" },
      today: { zh: "now", en: "now" },
      datetimePicker: { zh: "Datetime selection", en: "datetimePicker" }
    },
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "Mon", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),

    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    selectHour: new Date().getHours()
  }),
  watch:
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    }
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    showPicker() {
      this.$emit("update:is-show",true);

      var time = new Date(this.datetime).getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
      this.selectHour = new Date(time).getHours();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    onConfirmHour(n) {
      this.onSelectHour(n);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show",false);
    },
    setNow() {
      this.year = new Date().getFullYear();
      this.month = new Date().getMonth() + 1;
      this.day = new Date().getDate();
      this.selectDate = new Date(
        new Date().format("yyyy-MM-dd 00:00")
      ).getTime();
      this.selectHour = new Date().getHours();
    },
    confirmPicker() {
      this.$emit(
        "update:datetime",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.$emit(
        "picker-result",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectHour(n) {
      this.selectHour = n;
      this.$emit(
        "update:datetime",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
    },
    onSelectDate(time) {
      this.selectDate = time;
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.$emit(
        "update:datetime",
        new Date(time + this.selectHour * 3600000).format("yyyy-MM-dd hh:00")
      );
    }
  },
  mounted() {
    this.getMonthDay();
  }
};
</script>
<style lang="scss" scoped>
</style>

Using Picker

<template>
<section style="padding:16px;">
  <p>date1:{{date1}}</p>
  <date-picker :date.sync="date1" :is-show.sync="showDate1"></date-picker>
   <p>date2:{{date2}}</p>
    <date-picker1 :date.sync="date2" :is-show.sync="showDate2"></date-picker1>
     <p>date3:{{date3}}</p>
    <datetime-picker :datetime.sync="date3" :is-show.sync="showDate3"></datetime-picker>
</section>
</template>

<script>
Date.prototype.format = function(fmt)
{ //author: meizz
  var o = {
    "M+" : this.getMonth()+1, //Month "d+" : this.getDate(), //Day "h+" : this.getHours(), //Hours "m+" : this.getMinutes(), //Minutes "s+" : this.getSeconds(), //Seconds "q+" : Math.floor((this.getMonth()+3)/3), //Quarter "S" : this.getMilliseconds() //Milliseconds};
  if(/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").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;
}
import DateTimePicker from "./DateTimePicker";
import DatePicker from "./DatePicker";
import DatePicker1 from "./DatePicker1";
export default {
name:"PickerTest",
components:{
  'date-picker':DatePicker,
  'datetime-picker':DateTimePicker,
  'date-picker1':DatePicker1
},
data:()=>({
  showDate1:false,
  showDate2:false,
  showDate3:false,
  date1:new Date().format("yyyy-MM-dd"),
  date2:new Date().format("yyyy-MM-dd"),
  date3:new Date().format("yyyy-MM-dd hh:mm:ss"),
})
}
</script>

<style>

</style>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of Vue custom validation date and time selector
  • Ant design vue datepicker date selector Chinese operation
  • Instructions for using the date selection box mixed with the time selector in ant design vue
  • Implementation code of date linkage selector function based on Vue component
  • Use iView date picker in Vue.js and set the start time and end time verification function
  • Implementation of ElementUI date picker time selection range limit

<<:  Detailed explanation of creating a view (CREATE VIEW) and usage restrictions in MySQL

>>:  Detailed explanation of Docker daemon security configuration items

Recommend

Vue component to realize carousel animation

This article example shares the specific code of ...

WeChat applet date and time component (year, month, day, hour, and minute)

This article example shares the specific code of ...

JavaScript to achieve a simple magnifying glass effect

There is a picture in a big box. When you put the...

Docker image creation Dockerfile and commit operations

Build the image There are two main ways to build ...

The complete usage of setup, ref, and reactive in Vue3 combination API

1. Getting started with setUp Briefly introduce t...

Markup language - web application CSS style

Click here to return to the 123WORDPRESS.COM HTML ...

How to use macros in JavaScript

In languages, macros are often used to implement ...

Bug of Chinese input garbled characters in flex program Firefox

Chinese characters cannot be input in lower versio...

Some summary of html to pdf conversion cases (multiple pictures recommended)

Due to work requirements, I recently spent some t...

Solve the problem that the IP address obtained using nginx is 127.0.0.1

Get ip tool import lombok.extern.slf4j.Slf4j; imp...

A brief analysis of mysql index

A database index is a data structure whose purpos...

Using zabbix to monitor the ogg process (Windows platform)

This article introduces how to monitor the ogg pr...

WEB standard web page structure

Whether it is the background image or the text siz...