Create a JSON DateTime string with .NET.

For some strange reason, it doesn’t matter for this question, I need to create a JSON-compatible substring that represents DateTime and that will be manually entered into a large JSON string that will be parsed later by .NET DataContractJsonSerializer. I came up with the following method:

static readonly DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(DateTime)); private static string ToJsonString(DateTime time) { using (var memStream = new MemoryStream()) { s.WriteObject(memStream, time); return Encoding.UTF8.GetString(memStream.ToArray()); } } 

Is there any simpler way to do this or is it possible to optimize the code above? Or is there even an error in the code above?

It would also be great if I could do this without using the DataContractJsonSerializer, since line building would also be done in a pure .NET 1.1 process.

+4
source share
2 answers

Could you use the millisecond approach from the era? How is this extension method?

  public static class DateTimeExtensions { private static readonly DateTime Epoch = new DateTime(1970, 1, 1); public static string ToJson(this DateTime time) { return string.Format("\\/{0:0}\\/", (time - Epoch).TotalMilliseconds); } } 
+1
source

I would use NewtonSoft JSON and delegate responsibility for serializing DateTime. It supports DateTime serialization in ISO 8601 format (2008-04-12T12: 53Z, etc.) and is much more reliable than DataContractJsonSerializer.

You can use it to serialize your own objects or use it as a text editor to manually create JSON. It's easier to use than writing lines, trust me.

http://www.codeplex.com/Json

Alternatively, you can wrap this inside your ToString logic.

+1
source

All Articles