Format date DD-MM-YYYY string jquery [duplicate]

2

I have a 'DATAADMISSAO' field that receives DB information in the format below:

Iwouldliketoinputinthefollowingpattern:DD-MM-YYYY.

Belowisthejavascriptthatinsertsthedataintothefield:

functionsetSelectedZoomItem(selectedItem){varinfo=selectedItem.type.split("___");

    if (info.length > 1) { }

    if(selectedItem.type == "filiais"){
        $("#filial").val(selectedItem['nomefantasia']);
        $("#cnpj").val(selectedItem['cgc']);
        $("#codfilial").val(selectedItem['codfilial']);                         
    }else if(selectedItem.type == "setores"){
        $("#setor").val(selectedItem['nomefantasia']);              
    }else if(selectedItem.type == "chapafunc"){
        $("#chapafuncionario").val(selectedItem['CHAPA']);
        $("#nomefuncionario").val(selectedItem['NOME']);
        $("#cargofuncionario").val(selectedItem['FUNCAO']);
        $("#dataadmissao").val(selectedItem['DATAADMISSAO']);
        $("#salariofuncionario").val(selectedItem['SALARIO']);
    }

}
    
asked by anonymous 30.10.2018 / 20:27

3 answers

3

In addition to the aforementioned method of creating a date-type object, you can also simply format the string with a regular expression, like this:

var data = '2016-12-08 00:00:00.0';
var dataFormatada = data.replace(/(\d*)-(\d*)-(\d*).*/, '$3-$2-$1');
console.log(dataFormatada);
    
30.10.2018 / 21:10
0

There are a few ways to do this, I'll offer my way that can be a little tricky.

$("#dataadmissao").change(function() {
  var data = new Date($(this).val()); //cria um objeto de data com o valor inserido no input
  data = data.toLocaleDateString('pt-BR'); // converte em uma string de data no formato pt-BR
  $(this).val(data); // insere o novo valor no input
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type='text' id='dataadmissao'></input>
    
30.10.2018 / 20:48
0

Another way would be to use the javascript split javascript:

let data = "2016-12-08 00:00:00.0"; 
let split = data.split(' '); //separa a data da hora
let formmated = split[0].split('-');

console.log(formmated[2]+'-'+formmated[1]+'-'+formmated[0]);
    
30.10.2018 / 21:55