Q:

Issue with date.Parse()

I have enter invalid data such as "09/31/2016 10:10 AM"
but actually we dont have any 31th in september 2016, What date.parse() is doing that its calculating the next date "Oct 01, 2016 @ 10:10 AM" as output.

angular.module("myModule", [])
       .controller("myController", ['$scope', function ($scope) {
                    
           $scope.dDate = "09/31/2016 10:10 AM";
                    
           $scope.format = function () {
               $scope.display = Date.parse($scope.dDate);
           }
           $scope.format(); // invoke the format()
       }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule" >
    <div ng-controller="myController" ng-form="frm">
        <input type="text" name="name" style="width:250px;" ng-model="dDate" ng-change="format()" placeholder="MM/dd/YYYY hh:mm AM/PM" ng-pattern="/^(0[1-9]|1[012])[/]([123]0|[012][1-9]|31)[/](19[0-9]{2}|2[0-9]{3}) ([01][0-9]|2[0-3]):([0-5][0-9]) (AM|PM|am|pm)$/" />
        <div ng-show="!frm.name.$error.pattern">
            {{display | date : 'MMM dd, yyyy @ hh:mm a'}}
        </div>
        <div>Error : {{frm.name.$error}}</div>
    </div>
</body>

have I done anything wrong?

A:

You haven’t done anything wrong, but you have to write your own date validator if you want to check for rollover:
function checkDate(str) {
    var matches = str.match(/(\d{1,2})[- \/](\d{1,2})[- \/](\d{4})/);
    if (!matches) return;

    // parse each piece and see if it makes a valid date object
    var month = parseInt(matches[1], 10);
    var day = parseInt(matches[2], 10);
    var year = parseInt(matches[3], 10);
    var date = new Date(year, month - 1, day);
    if (!date || !date.getTime()) return;

    // make sure we have no funny rollovers that the date object sometimes accepts
    // month > 12, day > what's allowed for the month
    if (date.getMonth() + 1 != month ||
        date.getFullYear() != year ||
        date.getDate() != day) {
            return;
        }
    return(date);
}

You can see this post from which the code was liberally borrowed:  Is this a good way to check for a valid date in JavaScript?

