How to format the date of an input[date] in the format dd/mm/yyyy'?

Asked

Viewed 9,320 times

6

I have a page, built with Angularjs, that possessed a input[type=date].

Basically, what I want is to take this date and format (i.e., display to the user) using the format 'dd/MM/yyyy' (for example: 28/05/2015).

What’s the matter?

Today, are not all browsers that support the input[type=date]. Those that support (such as Chrome and Opera) format the date of the input in format 'dd/MM/yyyy', according to the browser’s own settings.

In browsers that do not support (such as Firefox and Safari), Angular uses the format yyyy-MM-dd to format the date of input. This format, which despite being readable, may not please the application users, who are used to the Brazilian format.

What is the solution?

In short, I couldn’t find any way to solve this.

Angular does not have any directive to set the input format. So, I tried to implement a directive that does this work for me by following some SO-EN posts:

The result of this was the following directive:

module.directive("input", ["$filter", function($filter) {
    return {
        require: "ngModel",
        restrict: "E",
        link: function(scope, element, attrs, ngModelController) {
            if (element.attr("type") != "date") {
                return;
            }

            if (verificaSeNavegadorNaoSuportaInputDate()) {
                ngModelController.$parsers.push(function(dataEmString) {
                    return converteStringParaData(dataEmString);
                });

                ngModelController.$formatters.push(function(data) {
                    return formataDataParaString(data);
                });
            }
        }
    };
}]);

With this directive, I can even format the date set in the model, but I can’t turn user input into an object Date. More precisely the $validator date of Ngmodelcontroller failure, since, supposedly, the value of the input is not a date.

To try to illustrate: using the above directive, the value of form.inputDoTipoDate.$error.date is equal to true.

Does anyone have any idea how I can implement/correct this directive?

  • See if it helps: http://answall.com/questions/6526/comorformatar-data-no-javascript.

  • 1

    Hehe, thanks for the link. But the problem is with the treatment of Angular.

  • Okay, it’s just that I remembered another topic, but I didn’t, so I found this one and I thought it might help... but even this other one I thought wasn’t about angular.

  • Use the momentjs both to display and to receive(convert) the value, there is no error.

  • 2

    Don’t use the momentjs for that. I hate people who to kill a fly suggest a cannon just because the cannon mark is in vogue... What you have to do is a filter, which returns the date as you want, and call this filter what is being done in the input.

  • Then just use it: <datepicker date-format="dd-MM-yyyy" date-min-limit="{{hoje}}">

  • Use ui-bootstrap (bootstrap written in Angularjs). It has a dot datepicker that solves your problem

  • Everything you need to know is well explained in the following link: https://angular-ui.github.io/bootstrap/#/datepicker

Show 4 more comments

2 answers

2

//Com js pode fazer da seguinte forma
// O input type=date vem no seguinte formato yyyy-mm-dd

// Para setar o valor caso esteja no formato dd/mm/yyyy

document.querySelector('[type=date]').value = '08/06/2017'.split('/').reverse().join('-');

// Para transformar de '2017-06-08' (formato devolvido no //document.querySelector('[type=date]').value) para //'08/06/2017'. Pode fazer isso: 

var brDate = '2017-06-08'.split('-').reverse().join('/');
var inputDate = '08/06/2017'.split('/').reverse().join('-');

console.log("br date: " + brDate);
console.log("input date: " + inputDate);
<input type="date" /> 

0

Your idea of creating a Directive might work if you use filters. I saw that Voce added the $filter service in your code, but you did not use it.

Take a look at the code below:

module.directive("input", ["$filter", function($filter) {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModelController) {
        if (element.attr("type") != "date") {
            return;
        }
        ngModelController.$parsers.push(function(data) {
          //View -> Model
          return data;
       });
       ngModelController.$formatters.push(function(data) {
          //Model -> View
          return $filter('date')(data, "DD-MM-YYYY");
        });
      }
    }
  };
}]);

I think I’m only missing.

I hope it helped.

  • I used it. I just abstracted the use of it to simplify sample code. But thanks for the answer. =)

Browser other questions tagged

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