js常用时间计算案例分享

前端开发过程中经常会涉及到对时间的一个处理,比如获取昨天,本周上周,本月这一类的信息传递给后端进行处理请求指定日期内的数据,这边提供一些时间处理的方式,作为参考。

手写声明一个处理最终结果的方法,方便后续更改时间格式 等操作。

//声明一个处理结果的方法,放点调用得出最终结果,便于以后更改返回值的具体格式等
getDateStr(now) {
				var year = now.getFullYear(); // 年
				var month = now.getMonth() + 1; // 月
				var day = now.getDate(); // 日
				if (day < 10) {
					day = '0' + day;
				}

				if (month < 10) {
					month = '0' + month;
				}
				return year + "-" + month + "-" + day;
			};

然后开始着手于对时间戳的处理:

        (请注意:这部分代码仅逻辑可用,其中变量名等需自行声明处理,否者会报错变量不存在哦,所以拿来主义选手请注意分辨)

1·当天的时间,这边没有进行加取(也就是比如今天是2022-01-01)那么获得的两个参数都是2022-01-01,看自己业务的实际情况处理吧


					var now = new Date();
					var nowDay = now.getDate();
					this.startTime = this.getDateStr(new Date(now.getTime() - 24 * 60 * 60 * 1000));
					this.endTime = this.getDateStr(new Date(now.getTime() - 24 * 60 * 60 * 1000));

2·昨天

var now = new Date();
					var nowDayOfWeek = now.getDay() == 0 ? 6 : (now.getDay() - 1);
					this.startTime = this.getDateStr(new Date(now.getTime() - nowDayOfWeek * 24 * 60 * 60 * 1000));
					this.endTime = this.getDateStr(now);

3·本周

var now = new Date();
					var nowDay = now.getDate();
					this.startTime = this.getDateStr(new Date(now.getTime() - now.getDay() * 24 * 60 * 60 * 1000 - 6 * 24 *
						60 * 60 * 1000));
					this.endTime = this.getDateStr(new Date(now.getTime() - now.getDay() * 24 * 60 * 60 * 1000));

4·上周

var now = new Date();
					var nowDay = now.getDate() - 1;
					this.startTime = this.getDateStr(new Date(now.getTime() - nowDay * 24 * 60 * 60 * 1000));
					this.endTime = this.getDateStr(now);

5·本月

let time = new Date();
let year = time.getFullYear() + '',
month = ((time.getMonth() + 1) + '').length == 1 ? '0' + ((time.getMonth() + 1) + '') :((time.getMonth() + 1) + ''),
day = time.getDate() + ''
let times = year + '-' + month + '-' + day;
this.endTime = this.startTime = times;

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值