¿Cómo analizar JSON para recibir un objeto Date en JavaScript?


Tengo una siguiente pieza de JSON:

\/Date(1293034567877)\/

Que es el resultado de este código. NET:

var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();

Ahora el problema al que me enfrento es cómo crear un objeto Date a partir de esto en JavaScript. Todo lo que pude encontrar fue una solución regex increíble (muchos contienen errores).

Es difícil creer que no haya una solución elegante ya que todo esto está en JavaScrip, me refiero al código JavaScript que intenta leer JSON (JavaScript Object Notation) que se supone que es un código JavaScript y en este momento resulta que no es porque JavaScript no puede hacer un buen trabajo aquí.

También he visto algunas soluciones de evaluación que no pude hacer funcionar (además de ser señalado como amenaza de seguridad).

¿Realmente no hay manera de hacerlo de una manera elegante?

Pregunta similar sin respuesta real:
Cómo analizar ASP.NET Formato de fecha JSON con GWT

Author: Community, 2010-12-22

16 answers

No existe una representación JSON estándar de las fechas. Debe hacer lo que @ jAndy sugirió y no serializar un DateTime en absoluto; simplemente envíe una cadena de fecha RFC 1123 ToString("r") o un número seconds-from-Unix-epoch, o algo más que pueda usar en JavaScript para construir un Date.

 42
Author: Jacob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 17:46:10

El JSON.la función parse acepta una función opcional DateTime reviver. Puedes usar una función como esta:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Luego llama

JSON.parse(somejsonstring,dateTimeReviver)

Y sus fechas saldrán bien

 106
Author: Tim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-24 19:44:01

Esta respuesta de Roy Tinker aquí :

var date = new Date(parseInt(jsonDate.substr(6)));

Como él dice: La función substr saca la parte "/Date (", y la función parseInt obtiene el entero e ignora el ")/" al final. El número resultante se pasa al constructor Date.

Otra opción es simplemente formatear su información correctamente en el lado ASP de modo que JavaScript pueda leerla fácilmente. Considere hacer esto para sus fechas:

DateTime.Now()

Que debe devolver un formato como esto:

7/22/2008 12:11:04 PM

Si pasa esto a un constructor JavaScript Date como este:

var date = new Date('7/22/2008 12:11:04 PM');

La variable date ahora tiene este valor:

Tue Jul 22 2008 12:11:04 GMT-0700 (Pacific Daylight Time)

Naturalmente, puede formatear este objeto DateTime en cualquier tipo de cadena/int que el constructor JS Date acepte.

 42
Author: treeface,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:58

Si usa el estilo JavaScript ISO8601 date en JSON, podría usar esto, desde MDN

var jsonDate = (new Date()).toJSON();
var backToDate = new Date(jsonDate);
console.log(jsonDate); //2015-10-26T07:46:36.611Z
 12
Author: LeeGee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 15:30:36

¿Qué tiene de malo:

new Date(1293034567877);

Esto me devuelve " Miércoles 22 de diciembre de 2010 16: 16: 07 GMT+0000 (Hora Estándar GMT)".

¿O necesitas sacar el número del json?

 6
Author: Psytronic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 17:17:12

Puede convertir la fecha JSON al formato de fecha normal en JavaScript.

var date = new Date(parseInt(jsonDate.substr(6)));
 4
Author: ViPuL5,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-20 06:31:13

Sé que este es un hilo muy antiguo, pero deseo publicar esto para ayudar a aquellos que se topan con esto como lo hice yo.

Si no te importa usar un script de terceros, puedes usar moment, js Entonces puedes usar .format() para darle formato a lo que quieras.

 2
Author: Eman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-30 15:05:26

AngularJS tampoco pudo analizar la cadena.NET JSON date /Date(xxxxxxxxxxxxx)/..

Corrí este problema formateando la fecha a su representación de cadena ISO 8601 en lugar de descargar el objeto Date directamente...

Aquí hay una muestra de ASP.NET Código MVC..

return Json(new { 
  date : DateTime.Now.ToString("O") //ISO 8601 Angular understands this format
});

Lo intenté RFC 1123 pero no funciona.. Angular trata esto como cadena en lugar de Fecha.

return Json(new { 
  date : DateTime.Now.ToString("R") //RFC 1123 Angular won't parse this
});
 1
Author: Rosdi Kasim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-25 05:43:56

No he usado.Net para cosas como esta. Si usted fue capaz de conseguir que imprima algo como lo siguiente, debería funcionar.

Tenga en cuenta que, a menos que esté analizando esa cadena JSON por algún otro medio o solo espere que los usuarios tengan navegadores modernos con un analizador JSON incorporado, necesita usar un marco JS o JSON2 para analizar la cadena JSON emitida por el servidor en un objeto JSON real.

// JSON received from server is in string format
var jsonString = '{"date":1251877601000}';

//use JSON2 or some JS library to parse the string
var jsonObject =  JSON.parse( jsonString );

//now you have your date!
alert( new Date(jsonObject.date) );

Wiki Link

Navegadores Modernos, tales como Firefox 3.5 e Internet Explorer 8, incluyen características especiales para analizar JSON. Como el soporte nativo del navegador es más eficiente y seguro que eval (), se espera que el soporte nativo de JSON sea incluido en el siguiente estándar ECMAScript.[6]


Enlace al archivo JSON2

Ejemplo en vivo

 0
Author: subhaze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 17:50:59

La respuesta a esta pregunta es, utilizar nuget para obtener JSON.NET luego usa esto dentro de tu método JsonResult:

JsonConvert.SerializeObject(/* JSON OBJECT TO SEND TO VIEW */);

Dentro de su vista simple haga esto en javascript:

JSON.parse(/* Converted JSON object */)

Si se trata de una llamada ajax:

var request = $.ajax({ url: "@Url.Action("SomeAjaxAction", "SomeController")", dataType: "json"});
request.done(function (data, result) { var safe = JSON.parse(data); var date = new Date(safe.date); });

Una vez que se ha llamado JSON.parse, puede poner la fecha JSON en una instancia new Date porque JsonConvert crea una instancia de tiempo ISO adecuada

 0
Author: Callum Linington,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-02 13:49:23

Como Callum mencionó, para mí, la mejor manera es cambiar el método del Controlador a string en lugar de JsonResult".

public string GetValues()
{
  MyObject.DateFrom = DateTime.Now;
  return JsonConvert.SerializeObject(MyObject);
}

Desde el método ajax puedes hacer algo como esto

 $.ajax({
 url: "/MyController/GetValues",
 type: "post",
 success: function (data) {
 var validData = JSON.parse(data);
//if you are using datepicker and you want set a format
$("#DateFrom").val($.datepicker.formatDate("dd/mm/yy", new Date(validData.DateFrom)));                                      
// if you want the date as returned
$("#DateFrom").val(new Date(validData.DateFrom))
}
});
 0
Author: onixpam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-24 19:55:58

Las citas son siempre una pesadilla. Respondiendo a su vieja pregunta, tal vez esta es la forma más elegante:

eval(("new " + "/Date(1455418800000)/").replace(/\//g,""))

Con eval convertimos nuestra cadena a código javascript. Luego eliminamos el"/", en la función reemplazar es una expresión regular. A medida que empezamos con nuevo entonces nuestras oraciones excecute esto:

new Date(1455418800000)

Ahora, una cosa que empecé a usar hace mucho tiempo, es valores largos que se representan en ticks... ¿Por qué? bueno, localización y dejar de pensar en cómo se configura la fecha en cada servidor o cada cliente. De hecho, yo también lo uso en bases de datos.

Quizás es bastante tarde para esta respuesta, pero puede ayudar a cualquiera aquí.

 0
Author: Gabriel Andrés Brancolini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-14 23:23:29

Usando la función eval funciona solo hay que eliminar la barra diagonal en la parte delantera y trasera.

var date1 = "/Date(25200000)/"
eval("new " + date1.substring(1, date1.length - 1));

Rindes Jue Ene 01 1970 00: 00: 00 GMT-0700 (Hora Estándar de la Montaña de Estados Unidos)

 0
Author: vernmic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 00:51:07
//
// formats a .net date into a javascript compatible date
//
function FormatJsonDate(jsonDt) 
{              
    var MIN_DATE = -62135578800000; // const

    var date = new Date(parseInt(jsonDt.substr(6, jsonDt.length-8)));                                                       
    return date.toString() == new Date(MIN_DATE).toString() ? "" : (date.getMonth() + 1) + "\\" + date.getDate() + "\\" + date.getFullYear(); 
}
 -1
Author: sunil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-18 13:36:59
function parseJsonDate(jsonDate) {

    var fullDate = new Date(parseInt(jsonDate.substr(6)));
    var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;

    var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
    var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();

    return currentDate;
};
 -1
Author: Muzafar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-06 10:58:13
function parseJsonDate(jsonDate) {

    var fullDate = new Date(parseInt(jsonDate.substr(6)));
    var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;

    var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
    var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();

    return currentDate;
};

/ / Utilice esta función

var objDate=parseJsonDate("\/Date(1443812400000)\/");
alert(objDate);
 -1
Author: Muzafar Hasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-16 13:56:11