需求:
- 获取过去七天到今天的时间段,需要字符串格式:
2020-4-13~2020-4-20; - 需要字符串格式:
2020-04-13~2020-04-20; - 需要的字符串格式 :
?start=2020-04-13&end=2020-04-20;
一、用getFullYear、getMonth、getDate方法
function getPastDate(num){ // num 是过去多少天,如过去七天,num为7;startTime 开始时间是过去;endTime结束时间是此刻;
let curDate=new Date(); // 获取当前时间对象
const startDate=new Date(curDate.getTime()-(num*24*3600*1000));// 获取当前的时间戳(毫秒),减去num转换的毫秒数,将得到的时间戳传给Date对象;便可获取到过去的那个时间点的时间对象;
const startTime=(startDate.getFullYear())+'-'+(startDate.getMonth()+1)+'-'+(startDate.getDate());// 获取过去的那个时间点的年月日,并用 短横线 - 连接;
return startTime;
}
function getCurrentDate(){
let curDate=new Date();
const endTime=(curDate.getFullYear())+'-'+(curDate.getMonth()+1)+'-'+(curDate.getDate());// 获取当前的时间点的年月日,并用短横线 - 连接;
return endTime
}
const startTime=getPastDate(7); // 如今天是 2020年4月20日,则startTime是2020-4-13;
const endTime=getCurrentDate();// endTime是今天,2020-4-20
二、 用toLocaleDateString方法
function getCurDate(){
const curDate=new Date().toLocaleDateString(); //当前时间, 获取到的格式是:2020/4/20
const endTime=curDate.replace(/[/]/g,'-');// 用短横线 - 全局替换特殊字符 斜线/
return endTime;
}
function getPastDate(num){
let cur=new Date(); // 获取当前时间对象
const pastDate=new Date(cur.getTime()-(num*24*3600*1000));
const startTime=pastDate.toLocaleDateString().replace(/[/]/g,'-');
return startTime;
}
getCurDate(); // 2020-4-20
getPastDate(7);// 2020-4-13
三、Date.now();方法,可获取到当前的毫秒数,
即 Date.now(); 等价于 new Date().getTime();,都是获取1970年1月1日截止到现在时刻的时间戳.
function getPastDate(num){
const pastDate=new Date(Date.now()-(num*24*3600*1000)); // 可获取到过去num天的时间对象
const startTime=pastDate.toLocaleDateString().replace(/[/]/g,'-');
return startTime;
}
getPastDate(7);// 2020-4-13
注意:
1. 用getFullYear、getMonth、getDate方法的时候,如果需要的是,2020-04-13 ,则还需对月份做一个处理;当月份小于10的时候,在月份前面加0,其余处理不做改变
const mon=(new Date().getMonth()+1)<10?`0${new Date().getMonth()+1}`:(new Date().getMonth()+1); // 如 :今天是2020年4月20日,则得到的mon为 04;
2. 用toLocaleDateString方法的时候,如果需要的是,2020-04-13 ,也需对数据进行处理
function getCurDate(){
const curDate=new Date().toLocaleDateString(); //当前时间, 获取到的格式是:2020/4/20
const date=curDate.split('/'); // 返回的格式是,["2020", "4", "20"]
const mon=date[1]<10?`0${date[1]}`:date[1];
return `${date[0]}-${mon}-${date[2]}`;// 显示的格式是:2020-04-20
}
function getPastDate(num){
let cur=new Date(); // 获取当前时间对象
const pastDate=new Date(cur.getTime()-(num*24*3600*1000));
const date=pastDate.toLocaleDateString().split('/');
const mon=date[1]<10?`0${date[1]}`:date[1];
return date[0]+'-'+mon+'-'+date[2]; // 显示的格式是:2020-04-13
}
getCurDate(); // 2020-04-20
getPastDate(7);// 2020-04-13

本文介绍使用JavaScript获取过去七天日期的三种方法:利用getFullYear、getMonth、getDate,toLocaleDateString以及Date.now()。每种方法均有详细代码示例,包括如何处理月份数字以确保两位数格式。
1308

被折叠的 条评论
为什么被折叠?



