Angular.js:输入日期显示日期-1天

时间:2016-03-17 14:14:18

标签: angularjs date

我有一张<input type="date">的表单。

当我在此输入中绑定数据时,它会显示日期-1天。

HTML:

<div class="input-field col s12">
    <label>Fecha Nacimiento </label>
    <input type="date" class="form-control" id="fnac" name="fnac" ng-model="unapersona.fnac">
</div>

控制器:

$scope.cargarpersona = function(id) {
    $http.get("modelos/personas_json.php?id="+id)
    .success(function(data) {
        $scope.unapersona = eval(data);
        //... Other data
        $scope.unapersona.fnac = new Date($scope.unapersona[0]["fnac"]);
        //... Other data
    })
    .error(function(data) {
        console.log('Error: ' + data);
    });
}

Screen Capture

3 个答案:

答案 0 :(得分:5)

解决!! 我只是将 ng-model-options =&#34; {timezone&#39; UTC&#39;} 放入输入日期

<input type="date" class="form-control" id="fnac" name="fnac" ng-model="unapersona.fnac" ng-model-options="{timezone:'UTC'}">

https://docs.angularjs.org/api/ng/directive/ngModelOptions

感谢您的回答和时间!

答案 1 :(得分:1)

你可能遇到了时区问题。请考虑以下代码(Plunkr here

<强> JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.aDate = new Date(Date.UTC(2016, 02, 17, 0, 0, 0));
  $scope.aSecondDate = new Date(2016, 02, 17, 0, 0, 0);
});

<强> HTML

<body ng-controller="MainCtrl">
    <h4>UTC Date</h4>
    <p>{{aDate}}</p>
    <h4>Local Date</h4>
    <p>{{aSecondDate}}</p>
  </body>

输出(在CET浏览器上):

UTC Date

"2016-03-17T00:00:00.000Z"

Local Date

"2016-03-16T23:00:00.000Z"

在第一种情况下,日期设置为UTC作为时区。

在第二种情况下,日期设置为local时区(您的浏览器设置),然后转换为UTC(此时距离CET相差1小时) ,因为这使得日期超过午夜,这是另一天。

答案 2 :(得分:0)

我认为date输入类型需要/而不是-,尚未经过测试,但希望它有效:

   .success(function(data) {
        $scope.unapersona = eval(data);

        var from_data = $scope.unapersona[0]["fnac"];
        var date_replace = from_data.replace(/-/g, '/');

        var date = new Date(date_replace );
        $scope.unapersona.fnac = ((date.getMonth() + 1) + '/' +  // JS months are 0 indexed and days are 1 indexed
                                   date.getDate() + '/' +                                                                                  
                                   date.getFullYear());
        })