前端周数计算

这篇博客介绍了一个业务场景,即如何从后端返回的格式如'2020年第21周'中,计算出该周的起始和结束日期,并转化为'年月日 时分秒'格式发送给后端。通过JavaScript和ES6的语法,博客详细展示了从字符串提取年份和周数,然后计算对应日期的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

业务场景:在界面上点击后端回传字段如‘2020年第21周’,此时需要往后端传所选周的始末时间(年月日 时分秒)

const selectTime = '2020年第21周'

const year1 = selectTime .split('年')[0]

        // 截取当前选择的周数

        const week = selectTime .split('第')[1].split('周')[0]

        // 起始日期

        const params = `${year1}-01-01 00:00:00`

        // 起始时间转时间戳

        const timeYear = (new Date(params)).getTime()

        // 获取当前年份一月一日周几(例如2020年一月一日为周三)

        const whichDay = (new Date(params)).getDay()

        // 根据第一周和非第一周获取选取周数,获取一月一日至当前周始所用时间

        const timeWeekStart = Number(week) === 1 ? ((Number(week) - 1) * 7) * 24 * 60 * 60 * 1000 : ((Number(week) - 1) * 7 - (whichDay - 1)) * 24 * 60 * 60 * 1000

        // 根据第一周和非第一周获取选取周数,获取一月一日至当前周终所用时间

        const timeWeekEnd = ((Number(week) - 1) * 7 + (7 - whichDay)) * 24 * 60 * 60 * 1000

        // 当前选择周的起始时间戳

        const totalTimeStart = new Date(timeYear + timeWeekStart)

        const yearStart1 = totalTimeStart.getFullYear()

        const monthStart1 = totalTimeStart.getMonth() + 1 > 9 ? totalTimeStart.getMonth() + 1 : `0${totalTimeStart.getMonth() + 1}`

        const dayStart1 = totalTimeStart.getDate() > 9 ? totalTimeStart.getDate() : `0${totalTimeStart.getDate()}`

        // 当前选择周的终止时间戳

        const totalTimeEnd = new Date(timeYear + timeWeekEnd)

        const yearStart2 = totalTimeEnd.getFullYear()

        const monthStart2 = totalTimeEnd.getMonth() + 1 > 9 ? totalTimeEnd.getMonth() + 1 : `0${totalTimeEnd.getMonth() + 1}`

        const dayStart2 = totalTimeEnd.getDate() > 9 ? totalTimeEnd.getDate() : `0${totalTimeEnd.getDate()}`

        this.searchParams.beginVisitDate = `${yearStart1}-${monthStart1}-${dayStart1} 00:00:00`

        this.searchParams.endVisitDate = `${yearStart2}-${monthStart2}-${dayStart2} 23:59:59`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值