javascript 获取当前月份的最后一天

87 阅读1分钟

在导出数据时,需要选择具体月份,使用element的月份组件,可以获取到当前月份的第一天,但是后端需要传当前月份的第一天和当前月份的最后一天,所以就需要前端进行处理,特此记录!

1.el-date-picker用法

<el-date-picker v-model="monthValue" size="small" value-format="yyyy-MM-dd" type="month" placeholder="选择需要导出考勤异常的月份" />

1.需要在data中定义monthValue和resultEndDate,resultEndDate用来赋值最后一天

2.获取的monthValue形式是2023-06-01

2.实现方法

// 导出数据f方法
async handleExport() {
  // 获取当前月的最后一天
  this.getMonthLast(this.monthValue);
  // 输入当前月最后一天
  console.log(this.resultEndDate);
},
// 获取的最后一天形式是中国标准时间,需要进行转换
getMonthLast(date) {
  const stringDate = new Date(date);
  let endDate = new Date(stringDate.getFullYear(), stringDate.getMonth() + 1, 0);
  this.newDate(endDate);
},
// 中国标准时间转换,返回数据格式为2023-06-30
newDate(time) {
  let date = new Date(time);
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  let d = date.getDate();
  d = d < 10 ? '0' + d : d;
  this.resultEndDate = y + '-' + m + '-' + d;
  return this.resultEndDate;
}