這兩天在做一個報表體統,其中涉及到了一個根據本周,上周,本月,上月的時間來進行查詢的問題,在這個我就教一下大家怎么實現,大家如果有更好的實現方法的,我也希望大家能說出來,我們交流交流.
首先呢,我寫了一個方法,能實現獲取本周,上周的開始時間,並且解決了跨年的問題
在這里先說明一下,月份,周幾都是從0開始的這一點是需要我們注意的.
本周,上周的開始結束時間
function getTime(n){
var now=new Date();
var year=now.getFullYear();
//因為月份是從0開始的,所以獲取這個月的月份數要加1才行
var month=now.getMonth()+1;
var date=now.getDate();
var day=now.getDay();
console.log(date);
//判斷是否為周日,如果不是的話,就讓今天的day-1(例如星期二就是2-1)
if(day!==0){
n=n+(day-1);
}
else{
n=n+day;
}
if(day){
//這個判斷是為了解決跨年的問題
if(month>1){
month=month;
}
//這個判斷是為了解決跨年的問題,月份是從0開始的
else{
year=year-1;
month=12;
}
}
now.setDate(now.getDate()-n);
year=now.getFullYear();
month=now.getMonth()+1;
date=now.getDate();
console.log(n);
s=year+"年"+(month<10?('0'+month):month)+"月"+(date<10?('0'+date):date)+"日";
return s;
}
/***參數都是以周一為基准的***/
//上周的開始時間
console.log(getTime(7));
//上周的結束時間
console.log(getTime(1));
//本周的開始時間
console.log(getTime(0));
//本周的結束時間
console.log(getTime(-6));
上個月的結束時間
解決思路:
1.用戶可以選擇是否傳入時間串,如果傳入的話,就按傳入的時間串定義時間,如果不是的話,就按當前時間來定義時間
2.判斷當前的月份或者要判斷的時間的當前月是否是1月份,如果是的話,那么年份就要-1,上個月的月份就是12月份
3.如果不是一月份的話,那么年份就不要-1,因為是同一年,所以只要月份-1就可以了
4.獲取最后一天思路是:獲取下個月第一天離1970年的毫秒數,然后減去一天時間的毫秒數,就是這個月的最后一天離1970年的毫秒數,根據這個毫秒數計算即可
function getMonth(dateStr){
let last_year=0,last_month=0,last_date=0,now=''
if(dateStr){
now=new Date(dateStr)
}
else{
now=new Date()
}
let year=now.getFullYear()
let month=(now.getMonth()+1).toString().padStart(2, '0')
let date=now.getDate().toString().padStart(2, '0')
if(month==1){
last_year=year-1
last_month=12
last_date=new Date(last_year,last_month,1)
return `${last_year}:${last_month}:${(new Date(last_date.getTime()-1000*60*60*24)).getDate()}`
}
else{
last_date=new Date(year,month-1,1)
return `${year}:${(month-1).toString().padStart(2,0)}:${(new Date(last_date.getTime()-1000*60*60*24)).getDate()}`
}
}