Loading date in millisecond format in Angularjs

Asked

Viewed 147 times

1

I need to press the input type="date" dates that are stored in millisecond format values.

Example

<label>Data de expiração:</label>
<input  class="form-control" type="date" name="dataexpiracao" ng-model="PontoRelevancia.dados_Evento.dataexpiracao | date:'dd/MM/yyyy' "> 

When I use this filter using the input type="text" it can put in the desired format , but using the input type="date"he doesn’t work.

What can I do to upload the date information in milliseconds using the type="date" ?

  • 1

    Have you tested new Date(PontoRelevancia.dados_Evento.dataexpiracao)?

  • @Henrique I believe the format is correct see this example , but like the author of the answer said , we have to convert to datatype that it appears there of good =|

  • 1

    @Sergio yes ! tested here in my function to retrieve the information it worked also but the ideal and use the directive even to preserve the original format.

1 answer

1


You need to implement, in this case, a directive that preserves the original format, while converting the value to a datatype that can be used with input type='datetime-local'.

Functional example to follow:

angular.module('myApp', [])
.directive('epochDatetime', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {
      ngModel.$formatters.push(function (value) {
        // transforma o modelo para um tipo Date().
        return new Date(value);
      });
     
      ngModel.$parsers.push(function(value) {
        // converte o valor Date do modelo para milissegundos pós-epoch.
        return value.getTime();
      });
    }
  };
})
.controller('myController', function($scope){
  $scope.dataReferencia = 1496268000000;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller='myController'>
    <input type="datetime-local" ng-model="dataReferencia" epoch-datetime id="exampleInput"/>
    <pre>{{dataReferencia}}</pre>
  </div>
</div>

  • Became top thank you !

  • @stringnome always a pleasure to help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.