JavaScript Serialization of Datetime in ASP.NET Is Not Giving a JavaScript Date Object

Javascript serialization of DateTime in asp.net is not giving a javascript date object?

This seems to work (Thanks Chris S for the idea). In the C# do a replace to remove the string wrapper from around the date object;

    using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI.WebControls;

namespace test
{
[ScriptService]
public partial class testing: System.Web.UI.Page
{
protected string strCaseID;
protected string jsonCase;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
strCaseID =Tools.GetQueryObject("id");
// get a complex object with dates, string, arrays etc.
jsonESHACase = new JavaScriptSerializer().Serialize(objCase.Get(strCaseID ))
.Replace("\"\\/Date(", "new Date(").Replace(")\\/\"", ")");
}
}
}
}

..and after removing the quotes and adding the new prefix to Date this js now works. Hooray!

testCase= <%= jsonESHACase %>;
if (testCase) {
document.write(testCase["ClosingDate"].format("MM dd yyyy"));
}

How to convert JavascriptSerializer serialized DateTime string to Javascript Date object

There is an answer that may help you:

Parsing Date-and-Times from JavaScript to C#

If you want to parse datetime string to datetime value with javascript you must use "new Date" like this:

var data = new Date("1355496152000");

Fixing JSON Date serialization from .Net web method

Your issue comes down to the server-side JavaScript serializer you are using; either JsonDataContractSerializer (default serializer for ASP.NET MVC) or NewtonSoft Json Serializer (default serializer for ASP.NET Web API).

For a visual example of this date mangling issue as well as possible solutions, check out JSON Dates are Different in ASP.NET MVC and Web API.

ASP.NET MVC JsonResult Date Format

Just to expand on casperOne's answer.

The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal "/" is the same as "\/", and a string literal will never get serialized to "\/" (even "\/" must be mapped to "\\/").

See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to "From JavaScript Literals to JSON")

One of the sore points of JSON is the
lack of a date/time literal. Many
people are surprised and disappointed
to learn this when they first
encounter JSON. The simple explanation
(consoling or not) for the absence of
a date/time literal is that JavaScript
never had one either: The support for
date and time values in JavaScript is
entirely provided through the Date
object. Most applications using JSON
as a data format, therefore, generally
tend to use either a string or a
number to express date and time
values. If a string is used, you can
generally expect it to be in the ISO
8601 format. If a number is used,
instead, then the value is usually
taken to mean the number of
milliseconds in Universal Coordinated
Time (UTC) since epoch, where epoch is
defined as midnight January 1, 1970
(UTC). Again, this is a mere
convention and not part of the JSON
standard. If you are exchanging data
with another application, you will
need to check its documentation to see
how it encodes date and time values
within a JSON literal. For example,
Microsoft's ASP.NET AJAX uses neither
of the described conventions. Rather,
it encodes .NET DateTime values as a
JSON string, where the content of the
string is /Date(ticks)/ and where
ticks represents milliseconds since
epoch (UTC). So November 29, 1989,
4:55:30 AM, in UTC is encoded as
"\/Date(628318530718)\/".

A solution would be to just parse it out:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));

However I've heard that there is a setting somewhere to get the serializer to output DateTime objects with the new Date(xxx) syntax. I'll try to dig that out.


The second parameter of JSON.parse() accepts a reviver function where prescribes how the value originally produced by, before being returned.

Here is an example for date:

var parsed = JSON.parse(data, function(key, value) {
if (typeof value === 'string') {
var d = /\/Date\((\d*)\)\//.exec(value);
return (d) ? new Date(+d[1]) : value;
}
return value;
});

See the docs of JSON.parse()

Custom JavaScriptConverter for DateTime?

JavaScriptSerializer can definitely do what you desire.

It's possible to customize the serialization performed by JavaScriptSerializer for any type by creating a custom converter and registering it with the serializer. If you have a class called Person, we could create a converter like so:

public class Person
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
}

public class PersonConverter : JavaScriptConverter
{
private const string _dateFormat = "MM/dd/yyyy";

public override IEnumerable<Type> SupportedTypes
{
get
{
return new[] { typeof(Person) };
}
}

public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
Person p = new Person();
foreach (string key in dictionary.Keys)
{
switch (key)
{
case "Name":
p.Name = (string)dictionary[key];
break;

case "Birthday":
p.Birthday = DateTime.ParseExact(dictionary[key] as string, _dateFormat, DateTimeFormatInfo.InvariantInfo);
break;
}
}
return p;
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Person p = (Person)obj;
IDictionary<string, object> serialized = new Dictionary<string, object>();
serialized["Name"] = p.Name;
serialized["Birthday"] = p.Birthday.ToString(_dateFormat);
return serialized;
}
}

And use it like this:

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new PersonConverter() });

Person p = new Person
{
Name = "User Name",
Birthday = DateTime.Now
};

string json = serializer.Serialize(p);
Console.WriteLine(json);
// {"Name":"User Name","Birthday":"12/20/2010"}

Person fromJson = serializer.Deserialize<Person>(json);
Console.WriteLine(String.Format("{0}, {1}", fromJson.Name, fromJson.Birthday));
// User Name, 12/20/2010 12:00:00 AM

C#: Wrong DateTime format passed to front end

I recommend using NewtonJson:

Add the package to your project

<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="..." />

and you can achieve it by adding some configurations to your Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
...

// Configure controllers.
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffZ"
});
});

...
}


Related Topics



Leave a reply



Submit