Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON DateTime from Newtonsoft's JSON Serializer

I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as:

/Date(1237588418563+0000)/ 

When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it.

Any ideas what I can do with this?

like image 492
tags2k Avatar asked Mar 21 '09 00:03

tags2k


People also ask

Does JSON accept DateTime?

Json library parses and writes DateTime and DateTimeOffset values according to the ISO 8601-1:2019 extended profile.

How do I format a Microsoft JSON date?

You can use this to get a date from JSON: var date = eval(jsonDate. replace(/\/Date\((\d+)\)\//gi, "new Date($1)")); And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

How does JSON format handle dates?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.


2 Answers

I came up with a different approach which might be useful to some. Basically I create my own CustomDateConverter that I call when I need it. The converter takes 2 parameters, a date format e.g. yyyy-MM-dd HH:mm:ss and a TimeZoneInfo, which allows me to convert the date from UTC to the user's time zone:

public class JSONCustomDateConverter : DateTimeConverterBase {     private TimeZoneInfo _timeZoneInfo;     private string _dateFormat;      public JSONCustomDateConverter(string dateFormat, TimeZoneInfo timeZoneInfo)     {         _dateFormat = dateFormat;         _timeZoneInfo = timeZoneInfo;     }     public override bool CanConvert(Type objectType)     {         return objectType == typeof(DateTime);     }      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)     {         throw new NotImplementedException();     }      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)     {         writer.WriteValue(TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(value), _timeZoneInfo).ToString(_dateFormat));         writer.Flush();     } 

You can use it like this:

 var jsonString = JsonConvert.SerializeObject(myObject, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Converters = new List<JsonConverter>() { new JSONCustomDateConverter("yyyy-MM-dd HH:mm:ss", loggedUser.Timezone) } }); 

Obviously you could remove anything related to time zone if you only want custom date formatting. Let me know it that helped!

like image 33
Johann Avatar answered Sep 19 '22 05:09

Johann


Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date.

public class LogEntry     {       public string Details { get; set; }       public DateTime LogDate { get; set; } }  [Test] public void WriteJsonDates() {       LogEntry entry = new LogEntry       {         LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),         Details = "Application started."       };         string defaultJson = JsonConvert.SerializeObject(entry);       // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}         string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());       // {"Details":"Application started.","LogDate":new Date(1234656000000)}    string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());       // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}     } 

Documentation: Serializing Dates in JSON with Json.NET

like image 196
James Newton-King Avatar answered Sep 17 '22 05:09

James Newton-King