4

For a strange reason that does not matter for this question I need to create a JSON compatible substring that represents a DateTime and that will be manually insterted into a larger JSON string that later will be parsed by .NET's DataContractJsonSerializer. I have come 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 can the code above be optimized in any way? Or is there even a mistake in the code above?

Also it would be really cool if I could do it without the use of DataContractJsonSerializer since the string building will also be done in a pure .NET 1.1 process.

2 Answers 2

1

Could you use the milliseconds-from-epoch time approach? Like 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);
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Is this really safe? How about UTC vs., localtime, I noticed DataContractJsonSerializer creates different strings for them. Whoknowswherelse it would create adifferent looking string....
I suppose you can convert both DateTime to UTC first before you do the calculations. Just do DateTime.ToUniversalTime() before you do the substraction.
1

I would use NewtonSoft JSON and delegate the responsibility of serializing the DateTime to that. It supports serializing DateTime to ISO 8601 format (2008-04-12T12:53Z etc) and is far more reliable than DataContractJsonSerializer.

You can use it to serialize native objects or use it as a text writer to manually generate JSON. It's easier to use this than writing strings out believe me.

http://www.codeplex.com/Json

Alternatively, you could wrap that inside your ToString logic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.