Format date AngularJS [duplicate]

3

I have a problem formatting the time that appears in View, it is coming as follows:

ButIwouldlikeittoappearintheformat"hh: mm: ss". The html code is as follows:

<input type="time" class="form-control" ng-disabled="!salvo" required ng-model="notaServico.dataEmissao" />

How do I format it in angular JS or even HTML itself?

Thank you.

    
asked by anonymous 28.08.2017 / 16:27

2 answers

6

Adapted answer from: how-to-format-one -data-in-format-dd-mm-yyyy

Use AngularJS filters

To format Angular dates, there is Angular Filter that is very useful and easy to use , either in view or controllers . filter can still be used to format any type of object. For date there are several possible combinations.

How to use filters?

In the javascript code (Directives, controllers, etc.)

$filter('filter')(array, expression, comparator)

How to format hours?

You can convert your Date object to any string based on settings, here are some examples:

  • HH hour with two digits (00-23) - 24 hours
  • H hour with a digit (0-23) - 24 hours
  • hh hour with two digits (01-12) - 12 hours
  • h hour with one digit (1-12) - 12 hours
  • mm minutes with two digits (00-59)
  • m minutes with a digit (0-59)
  • ss seconds with two digits (00-59)
  • s seconds with one digit (0-59)
  • See the full list at Angular documentation

How to apply this to your input?

You should inject the filter of angular service into your controller, and then format the value in the format you need.

angular
  .module('myApp', [])
  .controller('myController', myController);

myController.$inject = ['$scope', '$filter'];

function myController($scope, $filter) {
  var dataHora = new Date();
  $scope.hora = dataHora;
  $scope.horaFormatada = $filter('date')(dataHora, 'HH:mm:ss');
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp" ng-controller="myController">
  <label>Hora sem formato</label><br />
  <input type="time" ng-model="hora" /><br />
  <label>Hora formatada</label><br />
  <input type="time" ng-model="horaFormatada" />
</div>
    
28.08.2017 / 16:39
0

Try this code ( javascript ):

function time_format(d) {
    hours = format_two_digits(d.getHours());
    minutes = format_two_digits(d.getMinutes());
    seconds = format_two_digits(d.getSeconds());
    return hours + ":" + minutes + ":" + seconds;
}

function format_two_digits(n) {
    return n < 10 ? '0' + n : n;
}

I've used it once, I found in this answer .

Added after comment

You can call field formatting on onchange :

$("#id_input").on("change", function(){
    $(this).val(time_format($this).val());
});
    
28.08.2017 / 16:32