【JavaScript】获取当前时间的前一个小时,前一天/后一天,周一/周日,1号/最后一天:

1、中国标准时间=>yyyy-MM-dd hh:mm:ss:
/**
 * 时间格式化
 * @param value
 * @param fmt
 * @returns {*}
 */
export function formatDate(value, fmt) {
		console.log(value, fmt)
		//如果是数字
		let getDate = new Date(value);
		let o = {
			'M+': getDate.getMonth() + 1,
			'd+': getDate.getDate(),
			'h+': getDate.getHours(),
			'm+': getDate.getMinutes(),
			's+': getDate.getSeconds(),
			'q+': Math.floor((getDate.getMonth() + 3) / 3),
			'S': getDate.getMilliseconds()
		};
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		for (let k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
			}
		}
		return fmt;
	}

// 调用
formatDate(需要格式化的时间,'yyyy-MM-dd hh:mm:ss')

formatDate(需要格式化的时间,'yyyy-MM-dd')

formatDate(需要格式化的时间, 'hh:mm:ss') 
2、yyyy-mm-dd=>中国标准时间:
let date=new Date('2022-08-01')
console.log(date)  //Mon Aug 01 2022 08:00:00 GMT+0800 (中国标准时间)
3.js获取当前时间的前一个小时,前一天/后一天,周一/周日,1号/最后一天:

在这里插入图片描述

当前时间

let currentDate = new Date();//当前时间

前一个小时

let beforeOneHour=new Date(new Date().getTime() - 1 * 60 * 60 * 1000);

前一天/后一天

let preDate = new Date( new Date().getTime() - 24*60*60*1000); //前一天   =>前几天24*60*60*1000在乘以几即可

let nextDate = new Date( new Date().getTime() + 24*60*60*1000); //后一天  ,此时为中国标准时间

获取当前月的第一天和最后一天

//获取该月的第1天
let MonthFirstDay=new Date(new Date().getFullYear(), new Date().getMonth(), 1)

//使用new Date(year,month,0)的方式,可以获取该月的最后一天
let MonthLastDay=new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)

获取当前日期周一和周日

//获取当前日期周一和周日
let WeekFirstDay = this.getWeekDay('start')
let WeekLastDay = this.getWeekDay('end')

getWeekDay(type) {
	var date = new Date();
	var day = date.getDay() || 7;
	if (type == 'start') {
		return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day, date.getHours(), date.getMinutes(), date.getSeconds());
	} else {
		return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7 - day, date.getHours(), date.getMinutes(), date.getSeconds());
	}
},
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sun Peng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值