2012-02-28 93 views
5

(首先,請原諒我的英語,我是初學者)如何用js獲得一個月的4個星期一?

讓我解釋一下這種情況:

我想創建一個使用谷歌圖表工具(試一試的圖表,這是非常有幫助)。 這部分是不是真的很難...

問題出現時,我有一個具體的圖表需要在X軸四個星期的一個月:我想顯示在屏幕上只有四個星期一在這個月。

我已經有了currentMonth和currentYear變量,我知道如何獲得該月的第一天。我所需要的就是如何在一個數組中獲得一個月的四個星期一。所有這些都在同一個JavaScript文件中。

我在編程邏輯中迷失了方向,我看到很多解決方案都不適合我的情況。

所以,我有什麼是:

var date = new Date(); 
var currentYear = date.getFullYear(); 
var currentMonth = date.getMonth(); 
var firstDayofMonth = new Date(currentYear,currentMonth,1); 
var firstWeekDay = firstDayofMonth.getDay(); 

,我想有這樣的事情:

var myDates = 
[new Date(firstMonday),new Date(secondMonday), new Date(thirdMonday),new Date(fourthMonday)] 

感謝您的閱讀,如果你能幫助我... :)

Gaelle

+1

一個月可以有5個星期一。就像當前月份一樣(2012年2月)。 – pduersteler 2012-02-28 11:38:54

+1

好吧,2012年2月確實只有4個星期一,6日,13日,20日和27日(昨天)。它開始於星期三,結束於星期三..但我同意,一個月可能有5個星期一如2012年4月。是的,我必須記住這一事實,當我的代碼 – Gaelle 2012-02-28 11:53:54

+0

被我自己的日曆困惑時,我很抱歉。 – pduersteler 2012-02-28 12:08:32

回答

22

以下function將返回所有星期一爲C urrent月:

function getMondays() { 
    var d = new Date(), 
     month = d.getMonth(), 
     mondays = []; 

    d.setDate(1); 

    // Get the first Monday in the month 
    while (d.getDay() !== 1) { 
     d.setDate(d.getDate() + 1); 
    } 

    // Get all the other Mondays in the month 
    while (d.getMonth() === month) { 
     mondays.push(new Date(d.getTime())); 
     d.setDate(d.getDate() + 7); 
    } 

    return mondays; 
} 
+0

謝謝傑克拉克森,它解決了問題! – Gaelle 2012-02-28 12:54:11

+0

很高興幫助:-) – jabclab 2012-02-28 12:54:33

3

這將返回本月[M]的 第四 最後一個星期一在一年[Y]

function lastmonday(y,m) { 
var dat = new Date(y+'/'+m+'/1') 
    ,currentmonth = m 
    ,firstmonday = false; 
    while (currentmonth === m){ 
    firstmonday = dat.getDay() === 1 || firstmonday; 
    dat.setDate(dat.getDate()+(firstmonday ? 7 : 1)); 
    currentmonth = dat.getMonth()+1; 
    } 
    dat.setDate(dat.getDate()-7); 
    return dat; 
} 
// usage 
lastmonday(2012,3); //=>Mon Mar 26 2012 00:00:00 GMT+0200 
lastmonday(2012,2) //=>Mon Feb 27 2012 00:00:00 GMT+0100 
lastmonday(1997,1) //=>Mon Jan 27 1997 00:00:00 GMT+0100 
lastmonday(2012,4) //=>Mon Apr 30 2012 00:00:00 GMT+0200 

更通用的,這將提供最後的任何工作日月:

function lastDayOfMonth(y,m,dy) { 
var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6} 
    ,dat = new Date(y+'/'+m+'/1') 
    ,currentmonth = m 
    ,firstday = false; 
    while (currentmonth === m){ 
    firstday = dat.getDay() === days[dy] || firstday; 
    dat.setDate(dat.getDate()+(firstday ? 7 : 1)); 
    currentmonth = dat.getMonth()+1 ; 
    } 
    dat.setDate(dat.getDate()-7); 
    return dat; 
} 
// usage 
lastDayOfMonth(2012,2,'tue'); //=>Tue Feb 28 2012 00:00:00 GMT+0100 
lastDayOfMonth(1943,5,'fri'); //=>Fri May 28 1943 00:00:00 GMT+0200 
+0

謝謝,它非常有趣,我可能會在稍後使用它 – Gaelle 2012-02-28 12:51:42

相關問題