Change the format of the date I receive from YYYY-MM-DD to DD / MM / YYYY

3

In this function, of the Database I bring the date value in AAAA-MM-DD format, and what I want is that when receiving by AJAX the date format is changed to DD/MM/AAAA .

If someone like do it without using PHP to achieve it would be a great help.

function asignar_variables_formulario_editar_pedido(co_id_compra) {
  $.ajax({
    type: 'POST',
    url: '<?php echo base_url(); ?>co_compras/getCompra',
    data: 'co_id_compra=' + co_id_compra,
    dataType: 'json',
    success: function(resp) {
      $(".ed_fecha_pago_promesa").val(resp.co_fecha_pago_promesa);
    }
  });
}
    
asked by Cesar Vieyra 12.01.2017 в 19:38
source

4 answers

4

Solution using regular expressions

var texto = '2017-01-10';
var salida = formato(texto);
console.log(salida);

/**
 * Convierte un texto de la forma 2017-01-10 a la forma
 * 10/01/2017
 *
 * @param {string} texto Texto de la forma 2017-01-10
 * @return {string} texto de la forma 10/01/2017
 *
 */
function formato(texto){
  return texto.replace(/^(\d{4})-(\d{2})-(\d{2})$/g,'$3/$2/$1');
}
    
answered by 09.04.2017 / 22:43
source
4

a more elegant way can be this ...

   function convertDateFormat(string) {
        var info = string.split('-').reverse().join('/');
        return info;
   }
    
answered by 14.01.2017 в 06:02
3

You could do the following:

  • Obtain date data (eg: day, month, year ) by separating the string by the% - and then assemble the date in the desired order.

    So for example:

var dateString = '2017-01-10';
console.log(convertDateFormat(dateString));

// @param string (string) : Fecha en formato YYYY-MM-DD
// @return (string)       : Fecha en formato DD/MM/YYYY
function convertDateFormat(string) {
  var info = string.split('-');
  return info[2] + '/' + info[1] + '/' + info[0];
}
  • Or you could use a lib , for example, momentjs

var dateString = '2017-01-10';
console.log(moment(dateString).format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
    
answered by 12.01.2017 в 21:05
1
diaActual = new Date();

var day = diaActual.getDate();
var month = diaActual.getMonth()+1;
var year = diaActual.getFullYear();

fecha  = year + '' + month + '' + day;

Or arrange it as you like ...;)

    
answered by 30.08.2018 в 18:15