前端开发过程中经常会涉及到对时间的一个处理,比如获取昨天,本周上周,本月这一类的信息传递给后端进行处理请求指定日期内的数据,这边提供一些时间处理的方式,作为参考。
手写声明一个处理最终结果的方法,方便后续更改时间格式 等操作。
//声明一个处理结果的方法,放点调用得出最终结果,便于以后更改返回值的具体格式等
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;