如何在javascript中检测月份变化?

时间:2015-01-05 07:29:20

标签: javascript angularjs html5

我使用javascript获取当前日期,接下来的7天。现在我正在尝试找到检测这之间月份变化的方法。我的意思是,如果当前日期是12月31日,那将是1月之后的第二天。比如何获得新的一个月,并在我看来都显示 更新:现在我找到了获得新月的方法。现在我需要在月末日期之后添加这个月 我的意思是:Dec Tue 30,Wed 31,Jan Thu 1,Fri 2 ....
小提琴:http://jsfiddle.net/HB7LU/9763/
JS:

 function GetDates(startDate, daysToAdd) {
        var aryDates = [];
        for(var i = 0; i <= daysToAdd; i++) {
            var currentDate = new Date();
            $scope.currentMonth= MonthAsString(currentDate.getMonth());
            currentDate.setDate(startDate.getDate() + i);
            aryDates.push(DayAsString(currentDate.getDay()) + " " + currentDate.getDate() + " " );
        }

        return aryDates;
    }


    function MonthAsString(monthIndex) {
        var d=new Date();
        var month=new Array();
        month[0]="Jan";
        month[1]="Feb";
        month[2]="March";
        month[3]="April";
        month[4]="May";
        month[5]="June";
        month[6]="July";
        month[7]="Aug";
        month[8]="Sep";
        month[9]="Oct";
        month[10]="Nov";
        month[11]="Dec";

        return month[monthIndex];
    }

    function DayAsString(dayIndex) {
        var weekdays = new Array(7);
        weekdays[0] = "SUN";
        weekdays[1] = "MON";
        weekdays[2] = "TUE";
        weekdays[3] = "WED";
        weekdays[4] = "THU";
        weekdays[5] = "FRI ";
        weekdays[6] = "SAT";

        return weekdays[dayIndex];
    }

    var startDate = new Date();
    var aryDates = GetDates(startDate, 7);
    console.log(aryDates);
    $scope.totalDays = aryDates;

HTML:

 <div class="row" style="text-align:center;background-color: #930d14; color: white; height: 55px;">
            <div class="col" style="border-right: solid 1px #820d13;">
                <p style="transform: rotate(270deg);margin-top: 8px;font-size: 10px;font-weight: 600;text-transform: uppercase;">
                    {{currentMonth}}</p>
                <p ng-if="newMonth" style="transform: rotate(270deg);margin-top: 8px;font-size: 10px;font-weight: 600;text-transform: uppercase;">
                    {{newMonth}}</p>
            </div>

1 个答案:

答案 0 :(得分:1)

This answer应该让你到达那里:

function addDays(theDate, days) {
    return new Date(theDate.getTime() + days*24*60*60*1000);
}

var newDate = addDays(new Date(), 5);

然后你可以实例化两个不同的日子,并比较几个月:

var today = new Date();
var newDate = addDays(new Date(), 7);

function addDays(theDate, days) {
    return new Date(today.getTime() + days*24*60*60*1000);
}

var monthChange = (today.getMonth() < newDate.getMonth()) 
    || (today.getMonth() === 12 && newDate.getMonth() === 1)

console.log(monthChange);

从那里开始,你想让你的日期变得人性化。为此,您可以使用.toUTCString()将日期格式化为UTC,或使用库,或滚动您自己的方法。看起来AngularJS有built-in filters来格式化日期。

Moment.js是really useful, too