Bootstrap

【js】日期常用方法,如根据月份查询指定月份第一天和最后一天、处理日期格式,根据出生日期算年龄等持续更新

1:去除时分秒

在这里插入图片描述


        <template slot-scope="scope">
          <span >{{ scope.row.startDate }}--{{ scope.row.endDate }}</span>
      </template>
  timeFormat(date) {
      let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date);      
      return newDate[0];
    },

2:获取当天的年月日格式

           let date = new Date();        
          let formdate = this.formatDate(date);
          this.$set(this.form.dateTime, 0, formdate);
          this.$set(this.form.dateTime, 1, formdate);
       
 // 获取当天的年月日格式
    formatDate(value) {
      let y = value.getFullYear();
      let MM = value.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = value.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + MM + "-" + d;
    },

3、根据月份查询指定月份第一天和最后一天,传值给日期组件并查询列表数据

在这里插入图片描述
在这里插入图片描述

点击任意月,日期组件回显本年当前月的第一天和最后一天

 <div class="month">
          <div
            v-for="(item, index) in monthList"
            :key="index"
            class="monthClass"
            @click="getDate(item.value)"
          >
            {{ item.name }}
          </div>
        </div>
 queryParams: {
        pageNum: 1,
        pageSize: 30,
        startTime: "",//日期组件开始日期
        endTime: "",//日期组件结束日期
      
      },
  createTime: [],//日期组件绑的数组
    monthList: [
        { name: "全部", value: "" },
        { name: "一月", value: "1" },
        { name: "二月", value: "2" },
        { name: "三月", value: "3" },
        { name: "四月", value: "4" },
        { name: "五月", value: "5" },
        { name: "六月", value: "6" },
        { name: "七月", value: "7" },
        { name: "八月", value: "8" },
        { name: "九月", value: "9" },
        { name: "十月", value: "10" },
        { name: "十一月", value: "11" },
        { name: "十二月", value: "12" },
      ],
    getDate(value) {
      let time = new Date();
      let year = time.getFullYear() + ""; //当前年
      var str = year + value;
      this.createTime = this.getMonthStartEnd(str);
      this.queryParams.startTime = this.createTime ? this.createTime[0] : "";
      this.queryParams.endTime = this.createTime ? this.createTime[1] : "";
      console.log(this.createTime, "this.createTime");
    },
    getMonthStartEnd(vars) {  
      var arr = [];
      if (vars != null && vars != "") {
        var nyYear = vars.slice(0, 4);
        var nyMonth = vars.slice(4, vars.length);
        var firstDay = new Date(nyYear, nyMonth - 1);
        var lastDay = new Date(
          new Date(nyYear, nyMonth).valueOf() - 60 * 60 * 1000 * 24
        );
        var star =
          firstDay.getFullYear() +
          "-" +
          (firstDay.getMonth() + 1) +
          "-" +
          firstDay.getDate();
        var end =
          lastDay.getFullYear() +
          "-" +
          (lastDay.getMonth() + 1) +
          "-" +
          lastDay.getDate();
        arr = [star, end];
       
      }
      return arr;
    },
  },

4、同3,只是是根据月份查当前年对应月

getDate(value) {
      var str = "";
      if (value) {
        let time = new Date();
        let year = time.getFullYear() + ""; //当前年
        str = year + value;
      } else {
        str = "";
      }
      this.createTime = this.getMonthStartEnd(str);
      this.queryParams.startTime = this.createTime ? this.createTime[0] : "";
      this.queryParams.endTime = this.createTime ? this.createTime[1] : "";
    },
    getMonthStartEnd(vars) {   
      var arr = [];
      if (vars != null && vars != "") {
        var nyYear = vars.slice(0, 4);
        var nyMonth = vars.slice(4, vars.length);
        var firstDay = new Date(nyYear, nyMonth - 1); //nyMonth - 1,月份0-11
        var lastDay = new Date(
          new Date(nyYear, nyMonth).valueOf() - 60 * 60 * 1000 * 24
        );
        var firstMonth = firstDay.getMonth() + 1;
        var lastMonth = lastDay.getMonth() + 1;
        firstMonth = firstMonth < 10 ? "0" + String(firstMonth) : firstMonth;
        lastMonth = lastMonth < 10 ? "0" + String(lastMonth) : lastMonth;
        var star = firstDay.getFullYear() + "-" + firstMonth;
        var end = lastDay.getFullYear() + "-" + lastMonth;
        arr = [star, end];
      } else {
        let time = new Date();
        let year = time.getFullYear() + ""; //当前年
        var starm = year + "-" + "01";
        var endm = year + "-" + "12";
        arr = [starm, endm];
      }
      return arr;
    },

5、处理日期格式,字符串日期 ,如:‘20220803’,处理成’2022-08-03’

方法1:

this.invoiceDate = this.isYmd(row.dealcode);
   isYmd(date) {
      if (!date)  return 
        );
      var partten = /(\d{4})(\d{2})(\d{2})/;
      var formateDate = date.replace(partten, "$1-$2-$3");
      return formateDate;
      }

方法2:

this.invoiceDate = this.isYmd(row.dealcode);
   isYmd(value) {
      if (!value)  return 
        );
      if(value.length == 8){
      return value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8);
     } else if(value.length == 6){
         return value.substring(0, 4) + "-" + value.substring(4, 6);
   } else {
    return value;
  }
      }

6、处理日期格式,根据指定日期处理成‘yyyy-mm-dd’格式

this.invoiceDate = this.isYmd(row.dealcode);
   isYmd(date) {
 var d = new Date(date),
   month = "" + (d.getMonth() + 1),
     day = "" + d.getDate(),
    year = d.getFullYear();

     if (month.length < 2) month = "0" + month;
    if (day.length < 2) day = "0" + day;

    return [year, month, day].join("-");
      }

7、日期组件设置默认值,今天-两个月前的今天

    setDate() {
      let date = new Date()
      let formdate = this.formatymdDate(date)
      var beforeDate = date.setMonth(date.getMonth() - 2)
      beforeDate = this.timestampToTime(beforeDate)

      this.dateTime[0] = beforeDate
      this.dateTime[1] = formdate
      this.queryParams.startDate = this.dateTime[0]
      this.queryParams.endDate = this.dateTime[1]
    },
//获取当天年月日
formatymdDate(value) {
  let y = value.getFullYear()
  let MM = value.getMonth() + 1
  MM = MM < 10 ? '0' + MM : MM
  let d = value.getDate()
  d = d < 10 ? '0' + d : d
  return y + '-' + MM + '-' + d
}
// 时间戳转年月日
timestampToTime(timestamp) {
  var date = new Date(timestamp) //时间戳为10位需*1000,时间戳为13位的话不需乘1000
  let Y = date.getFullYear() + '-'
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  let D = date.getDate() + ' '

  return Y + M + D
}

8、根据出生日期算年龄(2023年10月10号更新~~)

通过日期组件的change事件,拿到值的格式为’xxxx-mm-ss‘格式

calenderonfirm(value) {
		const { fulldate} = value;
		data.userInfo.birthTime = fulldate;
		data.userInfo.age = getAge(fulldate)	
	}
getAge(year) {
		const today = new Date()//获取今年
		const birthday = new Date(year)//获取生日年
		let age = today.getFullYear() - birthday.getFullYear()
		let monthDiff = today.getMonth() - birthday.getMonth()
		let dateDiff = today.getMonth() - birthday.getDate()
		//对比今年和出生年的月份,小于0代表生日月还未到,或生日天还未到
		if (monthDiff < 0 || (monthDiff === 0 && dateDiff < 0)) {
			age--
		}
	
		return age
	}

9、直接给日期组件默认值,默认当前年的当前月份的第一天至当前年的当前月份的最后一天

             <el-date-picker
                v-model="createTime"
                @change="dataChange"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>


				createTime:[]

1、
首先,创建了一个Date对象now,它表示当前的日期和时间。
然后,使用now.getFullYear()获取当前年份,now.getMonth()获取当前月份。
接下来,使用new Date(year, month, day)构造函数创建了两个新的Date对象。
第一个新的Date对象firstDay代表当前月份的第一天。year参数传入了now.getFullYear(),即当前年份;month参数传入了now.getMonth(),即当前月份;day参数传入了1,表示第一天。
第二个新的Date对象lastDay代表当前月份的最后一天。year参数传入了now.getFullYear(),即当前年份;month参数传入了now.getMonth() + 1,即当前月份的下一个月(因为月份从0开始);day参数传入了0,表示上一个月的最后一天。

2、
直接拿到的格式是这样的:Mon Jan 01 2024 00:00:00 GMT+0800 (中国标准时间),要处理成‘yyyy-MM-dd’,所以需要格式化一下
首先,使用date.getFullYear()获取日期对象的年份,并将结果保存在变量year中。
然后,使用date.getMonth()获取日期对象的月份,并通过String()将其转换为字符串形式。由于月份是从0开始计数的,所以需要将结果加1,表示实际的月份。接着使用 padStart(2, “0”) 方法,在字符串前面补充0,使得月份的字符串长度始终为2位。
接下来,使用 date.getDate() 获取日期对象的日,并通过 String() 将其转换为字符串形式。同样使用 padStart(2, “0”) 方法,在字符串前面补充0,使得日期的字符串长度始终为2位。
最后,使用字符串模板 y e a r − {year}- year{month}-${day}将年、月、日连接起来,并作为函数的返回值。

created(){
this.init()
},
methods:{
init(){
// 获取当前日期
      const now = new Date();
      // 获取当前月的第一天
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
      // 获取当前月的最后一天
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      this.createTime = [this.formatDate(firstDay), this.formatDate(lastDay)];
},
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
}

;