生成任意周日期

<script>
window.onload = function () {
    var str = '';
    var list = CreateWeekDate('2012-05-01');
    
    for(var i = 0; i < 7; i++)
    {
        str += list.date[i] + ' ' + list.week[i] + '\n';
    }
    
    alert(str);
};

function CreateWeekDate(date)
{
    var now = date ? new Date(toDate(date)) : new Date();
    var n = now.getDay();
    var arrDate = [];
    var arrWeek = [];
    var result = {};
    
    for(var i = 0; i < 7; i++)
    {
        var date = new Date(now);
        date.setDate(now.getDate() - n + i + 1);
        arrDate.push(date.toLocaleFormat('%Y-%m-%d'));
        arrWeek.push(week(date));
    }
    
    result.date = arrDate;
    result.week = arrWeek;

    return result;
}

function toDate(date)
{
    var aDate = date.split("-");
    var result = new Date(aDate[0], (aDate[1] - 1), aDate[2]);
    
    return result;
}

function week(date)
{
    var dt = date ? new Date(date.getFullYear(), date.getMonth(), date.getDate()) : new Date();
    var weekDay = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    return weekDay[dt.getDay()];
}
</script>

posted @ 2012-08-03 22:26  baiezone  阅读(196)  评论(0编辑  收藏  举报