乐趣区

关于前端:js-根据n年第n周获取此周的开始和结束日期

// 格式化日期:yyyy-MM-dd
function formatDate(date) {var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;
    var myweekday = date.getDate();
    if (mymonth < 10) {mymonth = "0" + mymonth;}
    if (myweekday < 10) {myweekday = "0" + myweekday;}
    return (myyear + "-" + mymonth + "-" + myweekday);
}
//
function getXDate(year, weeks, weekDay) {
    weekDay %= 7;
    var date = new Date(year, "0", "1");
    var time = date.getTime();
    weekDay == 0 ? time += weeks * 7 * 24 * 3600000 : time += (weeks - 1) * 7 * 24 * 3600000;// 这里须要留神,当初这种模式是以周日为一周的完结,如果设定周日为一周的开始,去掉这个判断,抉择后者。date.setTime(time);
    return getNextDate(date, weekDay);
}
function getNextDate(nowDate, weekDay) {var day = nowDate.getDay();
    var time = nowDate.getTime();
    var sub = weekDay - day;
    time += sub * 24 * 3600000;
    nowDate.setTime(time);
    return nowDate;
}
// 留神,其中的参数:第一个为年,第二个为第几周,第三个为周数,0 为周日,1 为周一;alert("1983 第 1 周的星期 1 是:" + formatDate(getXDate(1983, 1, 1)));
alert("1983 第 1 周的星期日是:" + formatDate(getXDate(1983, 1, 0)));


退出移动版