2016-03-29 36 views
0

例如,在2016年3月27日至2016年4月2日的情況下,日期會在不同的月份中出現。如何獲得本週的第一天和最後一天,當天有幾天不同?

var curr = new Date; // get current date 
var first = curr.getDate() - curr.getDay(); 
var last = first + 6; // last day is the first day + 6 

var firstday = new Date(curr.setDate(first)).toUTCString(); 
var lastday = new Date(curr.setDate(last)).toUTCString(); 

回答

0

getDay方法返回在本週日的數,星期日爲0,星期六爲6.所以如果你的星期從星期天開始,只需從當前日期中減去當天的天數就可以開始,並添加6天ays即將結束,例如

function getStartOfWeek(date) { 
 
    
 
    // Copy date if provided, or use current date if not 
 
    date = date? new Date(+date) : new Date(); 
 
    date.setHours(0,0,0,0); 
 
    
 
    // Set date to previous Sunday 
 
    date.setDate(date.getDate() - date.getDay()); 
 
    
 
    return date; 
 
} 
 

 
function getEndOfWeek(date) { 
 
    date = getStartOfWeek(date); 
 
    date.setDate(date.getDate() + 6); 
 
    return date; 
 
} 
 
    
 
document.write(getStartOfWeek()); 
 

 
document.write('<br>' + getEndOfWeek()) 
 

 
document.write('<br>' + getStartOfWeek(new Date(2016,2,27))) 
 

 
document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))

0

我喜歡moment library對於這種事情:

moment().startOf("week").toDate(); 
moment().endOf("week").toDate(); 
+0

有沒有辦法做到這一點在JavaScript中沒有的時刻。 – anna

+0

我認爲你將不得不做一些像Zarana推薦的東西,將日期轉換爲整數值並將其作爲數字處理。 – Shaun

+0

答案應該包括一個解釋,並且不應該要求在問題中沒有提及或標記的庫。 – RobG

0

你可以試試這個:

var currDate = new Date(); 
day = currDate.getDay(); 
first_day = new Date(currDate.getTime() - 60*60*24* day*1000); 
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000); 
+0

要獲得一週中最後一天的價值,您必須從最大星期幾減去日價值:'last_day = new Date(currDate.getTime()+ 60 * 60 * 24 *(6 - day) * 1000);' – Shaun

相關問題