日期计算

1.输出今天是今年的第多少天,也可查询到年底还有多少天

function getDays(cur, prv) {
    return (Math.abs((new Date(cur)).getTime() - (new Date(prv)).getTime()) / (60*60*24*1000)).toFixed() // 日期时间戳相减获取差值,除于一天的时间戳,获取正整数
}
alert(getDays('2021-05-14', '2021-01-01'))
alert(getDays('2021-01-01', '2021-05-14')) // 因为添加了绝对值的计算,所以不涉及到日期前后顺序的校验

2.输出今天是今年的第多少周

  function getDays(cur, prv) {
    return (Math.abs((new Date(cur)).getTime() - (new Date(prv)).getTime() + 60*60*24*1000) / (7*60*60*24*1000)).toFixed()
  }
  alert(getDays('2021-05-17', '2021-01-01'))
3.输出两个时间段中的所有月份
function getYears(startDate, endDate) { // 获取两个年月之间的所有月份
    let [startYear, startMonth] = startDate.split('-')
    let [endYear, endMonth] = endDate.split('-')
    // 同一年的中间月份
    if (endYear === startYear) {
      return Array.from({length: endMonth - startMonth + 1}, (k, v) => `${endYear}-${(v + +startMonth + '').padStart(2, 0)}`)
    }
    // 非同年
    let allMonths = []
    // 开始年的月份
    Array.from({length: 13 - startMonth}, (k, v) => allMonths.push(`${startYear}-${(v + +startMonth + '').padStart(2, 0)}`))
    // 中间年月
    if (endYear - startYear > 1) {
      for (let year = +startYear + 1; year < endYear; year++) {
        Array.from({length: 12}, (k, v) => allMonths.push(`${year}-${(v + 1 + '').padStart(2, 0)}`))
      }
    }
    // 结束年月
    Array.from({length: +endMonth}, (k, v) => allMonths.push(`${endYear}-${(v + 1 + '').padStart(2, 0)}`))
    return allMonths;
}
getYears('2020-02', '2021-05')//["2020-02", "2020-03", "2020-04", "2020-05", "2020-06", "2020-07", "2020-08", "2020-09", "2020-10", "2020-11", "2020-12", "2021-01", "2021-02", "2021-03", "2021-04", "2021-05"]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值