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?

4
  • Please see this answer Commented Jul 5, 2017 at 19:02
  • 2
    @Arman C# and Javascript are different Commented Jul 5, 2017 at 19:05
  • 2
    Oops, I copied the wrong link, apologies for that. I meant this one https://stackoverflow.com/a/18821102. Commented Jul 5, 2017 at 19:12
  • @Arman now that helps a lot. thanks Commented Jul 5, 2017 at 19:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

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.