JavaScript date format

1

I'm having problems formatting the date. As a matter of version, I can not define a date type field, so I must define it type datetime and add several 0 to the end. I get a json this:

Object {fecha_desde: "2017-01-01 00:00:00.000", fecha_hasta: "2017-04-30 00:00:00.000"}

And my intent is this:

<script>
          $(document).ready(function(){
            $('#cuatrimestre').on('change',function(){
                var cuatrimestre = $(this).val();
                $.ajax({
                    url : "getCuatri.php",
                    dataType: 'json',
                    type: 'POST',
                    async : false,
                    data : { cuatrimestre : cuatrimestre},
                    success : function(data) {
                        console.log(data)
                        //userData = JSON.parse(data);
                        var desde = String(data.fecha_desde).split('-');
                        var fechaDesde = desde[1] + '-' + desde[2] + '-' + desde[0];
                        $('#desde').val(fechaDesde);
                        var hasta = String(data.fecha_hasta).split('-');
                        var fechaHasta = hasta[1] + '-' + hasta[2] + '-' + hasta[0];
                        $('#hasta').val(fechaHasta);
                        //$('#hasta').val(data.fecha_hasta);
                    }
                }); 
            });
         });
        </script>

But I get this:

01-01 00:00:00.000-2017
04-30 00:00:00.000-2017

In the test mode I have the date type field, it works perfectly for me.

    
asked by GAL 06.03.2017 в 20:31
source

2 answers

1

This does not work as expected:

String(data.fecha_desde).split('-');

Since it will separate three groups, that's why you see the time together with the month:

mes / dia / año tiempo

You can convert the date into text to a Date object and then the method toLocaleString to obtain only the month, day and year of the date. You can also use moment . The following example uses both forms.

Example

let fechas = {
  desde: '2017-01-01 00:00:00.000',
  hasta: '2017-04-30 00:00:00.000'
};

let desde = parseDate(fechas.desde);
let hasta = moment(fechas.hasta).format('MM-DD-YYYY');

console.log('Desde:', desde);
console.log('Hasta (moment):', hasta);
  
function parseDate (isodate) {
  return (
    new Date(isodate)
      .toLocaleString('en-US', {
        month: '2-digit',
        day: '2-digit',
        year: 'numeric'
      })
      .replace(/\//g, '-')
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
    
answered by 06.03.2017 / 21:26
source
2

Convert the object to Date in this way

var desde = new Date(data.fecha_desde);

and to obtain the value you can use .toLocaleDateString() that will return the date in d/m/yyyy

format

If you want to change the format in this case dd/mm/yyyy you would have to select a Zone in my case es-MX and then the options to consider:

{year: 'numeric', month: '2-digit', day: '2-digit' }

for more information about the options here

I'll give you your example

var data = {fecha_desde: "2017-01-01 00:00:00.000", fecha_hasta: "2017-04-30 00:00:00.000"}

console.log(data)
//userData = JSON.parse(data);

var options = {year: 'numeric', month: '2-digit', day: '2-digit' };

var desde = new Date(data.fecha_desde);
console.log(desde.toLocaleDateString("es-MX", options))
$('#desde').val(desde);

var hasta = new Date(data.fecha_hasta);
console.log(hasta.toLocaleDateString("es-MX", options))
$('#hasta').val(hasta);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 06.03.2017 в 20:44