Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js: Input date shows date -1 day

Tags:

date

angularjs

I have a form with <input type="date">.

When I bind data in this input, it shows me the date -1 day.

The 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>

The Controller:

$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

like image 702
Walter Lauxmann Avatar asked Dec 24 '22 07:12

Walter Lauxmann


2 Answers

Solved!! Just I put the ng-model-options = "{timezone 'UTC'} into the input date

<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

Thanks for yours answers and time!

like image 140
Walter Lauxmann Avatar answered Dec 27 '22 11:12

Walter Lauxmann


You're probably running into timezone problems. Consider the following Code (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>

Output (on a CET browser):

UTC Date

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

Local Date

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

In the first case the date is set with UTC as the timezone.

In the second case, the date is set with the local timezone (your browser's settings), and then converted to UTC (which at the moment differs by 1h from CET), and because that puts the date over midnight, this is a different day.

like image 22
R. Wenger Avatar answered Dec 27 '22 11:12

R. Wenger