js根据当前时间,获取本周一和本周日
js根据当前时间,获取本周一和本周日
·
const now = new Date()
const nowTime = now.getTime()
// getDay()返回0-6,其中0表示周日,需特殊处理
const day = now.getDay() > 0 ? now.getDay() : 7 // 表示当前是周几
const oneDayTime = 24 * 60 * 60 * 1000 // 一天的总ms
// 本周一时间戳
const MondayTime = nowTime - (day - 1) * oneDayTime
// 本周日时间戳
const SundayTime = nowTime + (7 - day) * oneDayTime
// 格式化时间
const monday = new Date(MondayTime)
const sunday = new Date(SundayTime)
// 可以通过自定义函数(format)格式化时间戳
console.log('当前日:', now, now.format('yyyy-MM-dd'))
console.log('本周一:', monday, monday.format('yyyy-MM-dd'))
console.log('本周日:', sunday, sunday.format('yyyy-MM-dd'))
结果如下
function format(format) {
let date = {
'y+': this.getFullYear(),
'm+': this.getMonth() + 1,
'd+': this.getDate(),
'H+': this.getHours(),
'M+': this.getMinutes(),
'S+': this.getSeconds(),
}
let i
fot (i in date) {
let re = new RegExp('(' + i + ')')
format = format.replace(re, () => date[k] < 10 ? '0' + date[k] : date[k])
}
return format
}
// format.call(new Date(), 'yyyy-mm-dd')
如果感觉上述的计算比较繁杂,可以利用dayjs来处理,直接安装使用即可
// 安装
npm install dayjs
// 引入
import dayjs from 'dayjs
// 或
const dayjs = require('dayjs')
// 使用
dayjs().format() // 2023-03-06T15:42:16+08:00
获取指定时间
// 获取当前时间YYYY-MM-DD
dayjs().format('YYYY-MM-DD') // 2023-03-06
// 昨天
dayjs().subtract(1, 'day').format('YYYY-MM-DD') // 2023-03-05
// 明天
dayjs().add(1, 'day').format('YYYY-MM-DD') // 2023-03-07
// 本月第一天
dayjs().startOf('month') // 2023-03-01
// 本月最后一天
dayjs().endOf('month') // 2023-03-31
// 本周第一天(这里要+1天,这里的1周=周日=>周六)
dayjs().startOf('week').add(1, 'day') // 2023-03-06
// 本周最后一天
dayjs().endOf('week').add(1, 'day') // 2023-03-12
更多推荐
已为社区贡献2条内容
所有评论(0)