计算某天开始的首年

这里主要是记录一下之前写的计算首年的方法里出现的问题

export function computedFirstYear(startTime){
    const [year, month, day] = startTime.split('-')
    const fullTime = new Date(new Date((year - 0 + 1), month, day).setDate(new Date((year - 0 + 1), month, day).getDate() - 1))
    return [startTime, fullTime.getFullYear() + '-' + (fullTime.getMonth() >= 10 ? fullTime.getMonth() : ('0' + fullTime.getMonth())) + '-' + (fullTime.getDate()>=10?fullTime.getDate():('0'+fullTime.getDate()))]
}

由于之前写的时候觉得new Date()里面的month虽然是从0开始计数的,但是输入和获取之后计算并没有出错,例如:

new Date(new Date(2024,10,9)).getMonth()得到的还是10
但实际解析一下new Date(new Date(2024,10,9))其实得到的是2024-11-09,只是getMonth拿到的月份是从0开始计数的,所以虽然是11月,但获取到的是10,因此也可以拿到结果,但实际含义却不同

正是因为我忽视这一点,因此这里计算首年时就出错了

//这里startTime就以2024-04-01为例,解析一下
new Date((year - 0 + 1), month, day).setDate(new Date((year - 0 + 1), month, day).getDate() - 1)

//new Date(2025,04,01)//实际拿到的是2025-05-01
new Date((year - 0 + 1), month, day).setDate(new Date((year - 0 + 1), month, day).getDate() - 1)就是给2025-05-01减去一天即2025-04-30,getMonth()为03,因此得到的是2025-03-30并不是我们要得到的,所以计算时还是要严谨一点

修改后的代码

export function computedFirstYear(startTime){
    const [year, month, day] = startTime.split('-')
    const fullTime = new Date(new Date((year - 0 + 1), month-1, day).setDate(new Date((year - 0 + 1), month-1, day).getDate() - 1))
    return [startTime, `${fullTime.getFullYear()}-${(fullTime.getMonth() + 1).toString().padStart(2, '0')}-${fullTime.getDate().toString().padStart(2, '0')}`]
}

startTime还是以2024-04-01为例,解析一下
new Date(2025,3,01)拿到的实际是2025-04-01,
new Date(new Date((year - 0 + 1), month-1, day).setDate(new Date((year - 0 + 1), month-1, day).getDate() - 1))就是2025-04-01减去一天即2025-03-31,getMonth()得到的是2,因为是从0开始计算,因此还要+1,那么就需要getMonth()+1,得到的就是2025-03-31

注:toString().padStart(2,‘0’)其实就是一个转换字符串并补0的一个写法,之前的一篇文章中有讲解过该方法,这里就不赘述了,有需要的小伙伴可以去找一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值