2012-07-09 48 views
1

我有一些朋友的生日,想按如下方式把它們分開:如何檢查日期是在本週內或本月內或下個月在JavaScript?

  • 生日落於本週內(在本週剩餘天從當天開始)。
  • 本月內的生日(從本日起的本月的剩餘日期內)。
  • 下個月內的生日。

所以我想知道如何在javascript中測試每個日期以查看它是否在本週/當前月份/下個月的剩餘日期內。

N.B:說我有m/d/Y(06/29/1990)格式的日期。

感謝

+1

[解析日期](http://stackoverflow.com/questions/1576753/parse-datetime-string-in-javascript)然後使用[存取](HTTP:// WWW .quackit.com/javascript/javascript_date_and_time_functions.cfm)Date對象並比較所需的字段。 – 2012-07-09 09:23:24

回答

3

將您的日期和當前時間Date對象,並用它進行比較。一些幹編碼:

var now = new Date() 
if (
    (check.getFullYear() == now.getFullYear()) && 
    (check.getMonth() == now.getMonth()) && 
    (check.getDate() >= now.getDate()) 
) { 
    // remanining days in current month and today. Use > if you don't need today. 
} 

var nextMonth = now.getMonth() + 1 
var nextYear = now.getFullYear() 
if (nextMonth == 12) { 
    nextMonth = 0 
    nextYear++ 
} 
if (
    (check.getFullYear() == nextYear) && 
    (check.getMonth() == nextMonth) 
) { 
    // any day in next month. Doesn't include current month remaining days. 
} 

var now = new Date() 
now.setHours(12) 
now.setMinutes(0) 
now.setSeconds(0) 
now.setMilliseconds(0) 
var end_of_week = new Date(now.getTime() + (6 - now.getDay()) * 24*60*60*1000) 
end_of_week.setHours(23) 
end_of_week.setMinutes(59) 
end_of_week.setSeconds(59) // gee, bye-bye leap second 
if (check >=now && check <= end_of_week) { 
    // between now and end of week 
} 
+0

任何方式來檢查檢查日期是否在本週的剩餘天數內? – flyleaf 2012-07-09 10:28:24

+0

是的。獲取當前時間,添加星期幾(6)和當前日期之間的差異,並使用此週末的新結束時間進行檢查。 – 2012-07-09 10:29:50

+0

非常感謝!這有助於很多! – flyleaf 2012-07-09 11:32:16

0

代碼使用解析日期是

var selecteddate = '07/29/1990'; 
var datestr = selecteddate.split('/'); 

var month = datestr[0]; 
var day = datestr[1]; 
var year = datestr[2]; 

var currentdate = new Date(); 
var cur_month = currentdate.getMonth() + 1; 
var cur_day =currentdate.getDate(); 
var cur_year =currentdate.getFullYear(); 

if(cur_month==month && day >= cur_day) 
{ 
alert("in this month"); 
} 

    else 
    { 
    alert("not in this month"); 
    } ​ 
+0

任何方式來獲得本週? – flyleaf 2012-07-09 10:04:12

相關問題