Format DD-MM-YYYY string jquery date

Asked

Viewed 6,987 times

2

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

inserir a descrição da imagem aqui

I would like to insert the following pattern: DD-MM-YYYY.

Below is the javascript that inserts the data into the field:

function setSelectedZoomItem(selectedItem) {
    var info = 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']);
    }

}

3 answers

4

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

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

0

There are some 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>

0

Another way would be using the function 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]);

Browser other questions tagged

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