Js中Date日期的使用

1.獲取今天的0時0分0秒(常用於開始日期的獲取)

var startDate= new Date(new Date().toLocaleDateString()); //Tue May 15 2018 00:00:00 GMT+0800 (中國標準時間)
 

2.獲取一個月前的日期

var lastM =new Date(new Date().setMonth(new Date().getMonth()-1));//Sun Apr 15 2018 09:18:08 GMT+0800 (中國標準時間)
 

3.獲取一個月前的0時0分0秒

var lastM_start =new Date(new Date(new Date().toLocaleDateString()).setMonth(new Date().getMonth()-1));
//Sun Apr 15 2018 00:00:00 GMT+0800 (中國標準時間)
 

4.獲取前一天的日期

var yesterday = new Date(new Date().setDate(new Date().getDate()-1));//Mon May 14 2018 09:26:39 GMT+0800 (中國標準時間)
 

5.獲取今天的23時59分59秒

var endDate = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1);
//Tue May 15 2018 23:59:59 GMT+0800 (中國標準時間) 
 

6.獲取昨天的23時59分59秒

var yes_endDate = new Date(new Date(new Date(
new Date().setDate(new Date().getDate()-1)).toLocaleDateString()).getTime()+24*60*60*1000-1);
//Mon May 14 2018 23:59:59 GMT+0800 (中國標準時間)

 

https://www.w3school.com.cn/jsref/jsref_obj_date.asp

 

 

示例:

獲取輸入時間的後一天日期並返回日期字符串

let endTime = '2020-01-01';
let endTime = formatDate(new Date(new Date(endTime).setDate(new Date(endTime).getDate()+1)));
console.log(endTime);//2020-01-02


//返回格式化日期 yyyy-MM-dd
function formatDate(date){
    return PrefixInteger(date.getFullYear(),4)+"-"+PrefixInteger(parseInt(date.getMonth()+1),2) +"-"+PrefixInteger(date.getDate(),2);
}
//數字轉字符串,前方自動補零
function PrefixInteger(num, n) {
    return (Array(n).join(0) + num).slice(-n);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章