Converting.NET Fecha y hora a JSON [duplicar]


Posible Duplicado:
Cómo formatear una fecha JSON?

Mi servicio webs devuelve una fecha y hora a una llamada jQuery. El servicio devuelve los datos en este formato:

/Date(1245398693390)/

¿Cómo puedo convertir esto en una fecha compatible con JavaScript?

Author: Community, 2009-06-19

10 answers

Lo que se devuelve es milisegundos desde epoch. Usted podría hacer:

var d = new Date();
d.setTime(1245398693390);
document.write(d);

Sobre cómo formatear la fecha exactamente como desee, consulte la referencia completa Date en http://www.w3schools.com/jsref/jsref_obj_date.asp

Puede eliminar los no dígitos analizando el entero ( como se sugiere aquí):

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

O aplicando la siguiente expresión regular (de Tominator en los comentarios):

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/; 
var m = re.exec(jsonDate); 
var d = new Date(parseInt(m[0]));
 238
Author: vahidg,
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 12:26:03

He estado usando este método por un tiempo:

using System;

public static class ExtensionMethods {
  // returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
  public static double UnixTicks(this DateTime dt)
  {
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
  }
}

Suponiendo que se está desarrollando contra.NET 3.5, es un copiar/pegar directamente. De lo contrario, puede portarlo.

Puede encapsular esto en un objeto JSON, o simplemente escribirlo en el flujo de respuesta.

En el lado Javascript / JSON, puede convertir esto a una fecha simplemente pasando los ticks a un nuevo objeto Date:

jQuery.ajax({
  ...
  success: function(msg) {
    var d = new Date(msg);
  }
}
 77
Author: Jeff Meatball Yang,
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
2011-11-16 17:22:28

Para analizar la cadena de fecha usando String.sustitúyase por referencia inversa:

var milli = "/Date(1245398693390)/".replace(/\/Date\((-?\d+)\)\//, '$1');
var d = new Date(parseInt(milli));
 33
Author: William Niu,
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-09-07 01:57:04

Si pasa un DateTime de un código. Net a un código javascript, C#:

DateTime net_datetime = DateTime.Now;

Javascript lo trata como una cadena, como "/Date(1245398693390)/":

Puede convertirlo como fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

O:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))
 17
Author: ytl,
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-29 08:27:12

Si tienes problemas para obtener la información del tiempo, puedes probar algo como esto:

    d.date = d.date.replace('/Date(', '');
    d.date = d.date.replace(')/', '');  
    var expDate = new Date(parseInt(d.date));
 16
Author: davidmdem,
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-03-09 18:14:38

La conversión de 1970,1,1 necesita el doble redondeado a cero decimales creo

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);

En el lado del cliente utilizo

new Date(+data.replace(/\D/g, ''));
 11
Author: Flash,
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
2011-10-03 23:21:36

Http://stevenlevithan.com/assets/misc/date.format.js

var date = eval(data.Data.Entity.Slrq.replace(/\/Date\((\d )\)\//gi, "new Date($1)"));  
alert(date.format("yyyy-MM-dd HH:mm:ss"));  
alert(dateFormat(date, "yyyy-MM-dd HH:mm:ss"));  
 7
Author: harry,
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
2011-09-13 20:57:21

Puedes probar una biblioteca de terceros como json.net Hay documentación en el sitio del proyecto. No dicen que requiere .net 3.5.

De lo contrario hay otro llamado Nii.json que creo que es un port de Java. He encontrado un enlace a ella en este blog

 6
Author: Dave Archer,
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
2009-06-19 08:11:52

Todas las respuestas anteriores indican que puedes hacer lo siguiente:

var d = eval(net_datetime.slice(1, -1));

Sin embargo, esto no funciona en Chrome o FF porque lo que se evalúa literalmente es:

// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);

La forma correcta de hacer esto es:

var d = eval("new " + net_datetime.slice(1, -1)); // which parses to

var d = new Date([epoch timestamp]); 
 5
Author: cowmoo,
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
2011-06-10 18:50:37

Pensé en agregar mi solución que he estado usando.

Si está utilizando el System.Web.Script.Serialization.JavaScriptSerializer() entonces la hora devuelta no va a ser específica para su zona horaria. Para arreglar esto, también querrá usar dte.getTimezoneOffset() para volver a su hora correcta.

String.prototype.toDateFromAspNet = function() {
    var dte = eval("new " + this.replace(/\//g, '') + ";");
    dte.setMinutes(dte.getMinutes() - dte.getTimezoneOffset());
    return dte;
}

Ahora solo llamarás

"/Date(1245398693390)/".toDateFromAspNet();

Vie Jun 19 2009 00: 04: 53 GMT-0400 (Eastern Daylight Time) {}

 4
Author: used2could,
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-07 02:36:07