如何在javascript中查看当前一周或当前月份或下个月的日期?

时间:2012-07-09 09:19:37

标签: javascript jquery date

我有一些朋友的生日,并希望将它们分开如下:

  • 当前一周内的生日(从当天开始的本周剩余天数内)。
  • 生日在当月内(从当天开始的当月剩余天数内)。
  • 生日在下个月内。

所以我想知道如何在javascript中测试每个日期,看它是否在当前周/当月/下个月的剩余天数内。

N.B:我说那些日期是m / d / Y(06/29/1990)格式。

由于

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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");
   }    ​