3

I parse c# object that has DateTime property with JsonNet and then I post it to the server. But it returns that the date format is wrong. It request to be with format like this:

"/Date(1327572000000-1000)/"

How can I convert c# DateTime to this format?

mister_giga
  • 560
  • 1
  • 15
  • 37

2 Answers2

5

Since you asked how to serialize with this format using JSON.NET:

// Set the DateFormatHandling wherever you are configuring JSON.Net.
// This is usually globally configured per application.
var settings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

// When you serialize, DateTime and DateTimeOffset values will be in this format.
string json = JsonConvert.SerializeObject(yourDateTimeValue, settings);

However, I highly recommend you do NOT use this format unless you absolutely have to, usually for purposes of compatibility with old code. The ISO-8601 format is preferred (de facto) format for dates and times in JSON.

See also: On the nightmare that is JSON Dates.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
0

This is how WCF essentially serializes DateTime values (note that non-UTC values include information about current time zone)

public static string MsJson(DateTime value)
{
    long unixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
    long ticks = (value.ToUniversalTime().Ticks - unixEpochTicks) / 10000;

    if (value.Kind == DateTimeKind.Utc)
    {
        return String.Format("/Date({0})/", ticks);
    }
    else
    {
        TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
        string sign = ts.Ticks < 0 ? "-" : "+";
        int hours = Math.Abs(ts.Hours);
        string hs = (hours < 10) 
            ? "0" + hours 
            : hours.ToString(CultureInfo.InvariantCulture);
        int minutes = Math.Abs(ts.Minutes);
        string ms = (minutes < 10) 
            ? "0" + minutes 
            : minutes.ToString(CultureInfo.InvariantCulture);
        return string.Format("/Date({0}{1}{2}{3})/", ticks, sign, hs, ms);
    }
}
Aloraman
  • 1,389
  • 1
  • 21
  • 32