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

Day.js中文网
js 获取昨天,今天,本周,上周,季度等时间范围

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值