JS判断日期是否在同一个星期内,和同一个月内

/*

*判断是否在同一个星期里

*date:时间字符串

*return:true/false

*/

function SameWeek(date) {    

var date1 = new Date(date.replace(/-/g, "/"));         //将传入的时间字符串转换成时间对象    

var date2 = new Date();     //当前时间    

var curWeek = date2.getDay();           //获取当前星期几    

var monday = GetDate((curWeek), 1); //计算出星期一    

var sunday = GetDate((7 - curWeek), 2); //计算出星期天

    if (date1.getTime() < monday.getTime() || date1.getTime() > sunday.getTime()) {        

return false;       //不在同一个星期内    

} else {        

return true;        //在同一个星期内    

}

}

/*

*判断是否在同一个月

*date:时间字符串

*return:true/false

*/

function SameMonth(date) {    

var date1 = new Date(date.replace(/-/g, "/"));         //将传入的时间字符串转换成时间对象    

var date2 = new Date();            //当前时间    

var curDay = date2.getDate();           //获取当前几号    

var firstDay = GetDate((curDay), 1);                                //计算出当月第一天    

var lastDay = GetDate((getDaysInMonth(date2.getFullYear(), date2.getMonth() + 1) - curDay), 2);    //计算出当月最后一天

    if (date1.getTime() < firstDay.getTime() || date1.getTime() > lastDay.getTime()) {        

return false;       //不在同一个月内    

} else {        

return true;        //在同一个月内    

}

}

/*

*获取某年某月有多少天

*/ function getDaysInMonth(year, month) {    

month = parseInt(month, 10) + 1;    

var temp = new Date(year + "/" + month + "/0");    

return temp.getDate();

}

/*

*获取当前日期前N天或后N日期(N = day)

*type:1:前;2:后

*/

function GetDate(day, type) {    

var zdate = new Date();    

var edate;    

if (type == 1) {        

edate = new Date(zdate.getTime() - (day * 24 * 60 * 60 * 1000));    

} else {        

edate = new Date(zdate.getTime() + (day * 24 * 60 * 60 * 1000));   

  }    

return edate;

}

文章转载来源:JS判断日期是否在同一个星期内,和同一个月内 - 李信华 - 博客园

猜你喜欢

转载自blog.csdn.net/weixin_46408500/article/details/125515938