JavaScript date format


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:

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

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

2 answers


This does not work as expected:


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.


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=""></script>
answered by 06.03.2017 / 21:26

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


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"}

//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))

var hasta = new Date(data.fecha_hasta);
console.log(hasta.toLocaleDateString("es-MX", options))
<script src=""></script>
answered by 06.03.2017 в 20:44