獲取N天前的時間( 過去七天的年月日、toLocaleDateString的應用 、獲取時間段字符串,Date.now()和new Date().getTime()的使用 )

需求:

  1. 獲取過去七天到今天的時間段,需要字符串格式:2020-4-13~2020-4-20 ;
  2. 需要字符串格式:2020-04-13~2020-04-20 ;
  3. 需要的字符串格式 :?start=2020-04-13&end=2020-04-20;

一、用getFullYeargetMonthgetDate方法

	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.getFullYeargetMonthgetDate方法的時候,如果需要的是,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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章