javascript - date.Parse() 的问题

标签 javascript html angularjs

我输入了无效数据,例如“09/31/2016 10:10 AM”

但实际上我们在 2016 年 9 月没有任何 31 号,date.parse() 正在做什么,它计算下一个日期“Oct 01, 2016 @ 10:10 AM”作为输出。

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>

我做错了什么吗?

最佳答案

你没有做错任何事,但如果你想检查翻转,你必须编写自己的日期验证器:

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);
}

你可以看到这篇文章,其中代码被大量借用:Is this a good way to check for a valid date in JavaScript?

关于javascript - date.Parse() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145842/

相关文章:

javascript - 二维弹道?

javascript - 如何在状态之间为图像设置动画

angularjs - Web API 通过 URL 加载,但从 Angular 脚本中获取错误 404

angularjs - 如何检查是否已将表达式属性提供给指令?

javascript - 在 AWS Lambda 中监听 Firebase 数据库超时

javascript - 删除 node.js 数组中具有相同开头的项

javascript - 我该如何选择这个li项?

html - Django 的什么功能可以使文本看起来更短?

php - 如何在成功提交表单后在 div 中创建成功消息?

javascript - JS文件中的System.register是什么意思?