2016-02-08 56 views
0

我如何通過JavaScript獲取上個星期四的日期?JavaScript 獲取上個星期四的日期

如果星期四是今天,那麼得到-7天。

之後,格式輸出像'2016年4月17日'。

+4

雖然我討厭成爲「那個人」,但到目前爲止你還有什麼嘗試? –

+0

你應該看看JavaScript中的Date對象API,看看你得到了多少。 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date – ToastyMallows

+0

找到當天並從今天減去'currentDay + 3' – Rajesh

回答

-1
var weekdays = [ "Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat" ]; 

function getDateForLastOccurence(strDay) 
{ 
    var date = new Date(); 
    var index = weekDays.indexOf(strDay); 
    var difference = date.getDay() - index; 
    if (difference < 0) 
    { 
     difference = -7 - difference; 
    } 
    date.setDate(date.getDate() + difference); 
    return date; 
} 

getDateForLastOccurence("Tue"); 
getDateForLastOccurence("Thurs"); 
0

首先,它會更容易通過共享代碼來幫助你;)

您可以通過使用該方法Date.getDay()其返回一週的當天上週四得到。

像這樣:

var now = new Date(); 
var daysAfterLastThursday = (-7 + 4) - now.getDay(); // 7 = number of days in week, 4 = the thursdayIndex (0= sunday) 
var currentMs = now.getTime(); 
var lastThursday = new Date(currentMs + (daysAfterLastThursday * 24 * 60 * 60 * 1000)); 
alert("Last Thursday : " + lastThursday); 

jsFiddle

0

簡單的,你可以自己做。

  1. 查找當前日d
  2. 由3
  3. 國防部步驟2的結果,通過使用7添加d(結果%7)
  4. 如果步驟3的結果是0減去7從今天的日期,否則從今天的日期中減去第3步的結果。
相關問題