js | 计算某天周一和周日的日期| 获取某年某月的最后一天| 计算某日是第几周| 获取某月的上个月 | 时间日期转换为‘yyyy-mm-dd‘格式

  1. 计算周一的日期

getMondayofWeek (date) {
  // date参数为Date格式
  const day = date.getDay() || 7;
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day);
}
  1. 计算周日的日期

getSundayofWeek (date) {
  // date参数为Date格式
  const day = 7 - (date.getDay() || 7);
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + day);
},
  1. 获取某年某月的最后一天

getMonthFinalDay (year, month) {
  // year, month是字符串格式
  let day = '';
  if (year == null || year === undefined || year === '') {
    year = new Date().getFullYear();
  }
  if (month == null || month === undefined || month === '') {
    month = new Date().getMonth() + 1;
  }
  day = new Date(new Date(year, month).setDate(0)).getDate();
  return year + '-' + month + '-' + day
},
  1. 计算某日是第几周

getMonthWeek (a, b, c) {
  // 参数是number格式,例如:new Date().getYullYear()返回数字格式,abc对应年月日
  const date = new Date(a, parseInt(b) - 1, c)
  const day = date.getDay() || 7
  const d = date.getDate()
  return Math.ceil((d + 6 - day) / 7)
},
  1. 获取某月的上个月

getPreMonth (yearmonth) {
  // yearmonth是'yyyy-mm'格式
  const arr = yearmonth.split('-')
  const year = arr[0]
  const month = arr[1]
  let year2 = year;
  let month2 = parseInt(month) - 1;
  if (month2 === 0) {
    // 1月的上一月是前一年的12月
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  if (month2 < 10) {
    // 10月之前都需要补0
    month2 = '0' + month2;
  }
  return year2 + '-' + month2;
},
  1. 时间日期Date格式转换为'yyyy-mm-dd'格式

dateformat (date) {
  // date为Date格式
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  month = (month > 9) ? month : ('0' + month)
  day = (day < 10) ? ('0' + day) : day
  return year + '-' + month + '-' + day
},
  1. 时间戳返回 yyyy-MM-dd 格式字符串

dateToYYYYMMDD (date) {
  // date为时间戳格式
  const time = new Date(date);
  const y = time.getFullYear();
  let m = (time.getMonth() + 1);
  m = m > 9 ? m : '0' + m;
  let d = time.getDate();
  d = d > 9 ? d : '0' + d;
  return y + '-' + m + '-' + d
},

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值