How to convert DateTime from JSON to C#? [duplicate]

Question!

Possible Duplicate:
How to convert UNIX timestamp to DateTime and vice versa?

I've got the following class:

[DataContractAttribute]
public class TestClass
{
  [DataMemberAttribute]
  public DateTime MyDateTime { get; set; }
}

Here's the JSON:

{ "MyDateTime":"1221818565" }

The JSON is being returned from a PHP webservice.

What I need to do, is convert that epoch string into a valid C# DateTime. What's the best way of doing this?

I can do this:

[IgnoreDataMemberAttribute]
public DateTime MyDateTime { get; set; }

[DataMemberAttribute(Name = "MyDateTime")]
public Int32 MyDateTimeTicks
{
  get { return this.MyDateTime.Convert(...); }
  set { this.Created = new DateTime(...); }
}

But the trouble with this is, the MyDateTimeTicks is public (changing it to private causes an exception in the serialization process)



Answers
private DateTime ConvertJsonStringToDateTime(string jsonTime)
        {
            if (!string.IsNullOrEmpty(jsonTime) && jsonTime.IndexOf("Date") > -1)
            {
                string milis = jsonTime.Substring(jsonTime.IndexOf("(") + 1);
                string sign = milis.IndexOf("+") > -1 ? "+" : "-";
                string hours = milis.Substring(milis.IndexOf(sign));
                milis = milis.Substring(0, milis.IndexOf(sign));
                hours = hours.Substring(0, hours.IndexOf(")"));
                return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToInt64(milis)).AddHours(Convert.ToInt64(hours) / 100);                 
            }

            return DateTime.Now;
        }
By : yossi


I know your question was for PHP, but I just wanted to note a "gotcha" for .NET JSON: it appears that .NET gives you the date in "milliseconds since epoch" (as opposed to seconds). In this case, the AddSeconds line should be: unixEpoch.AddMilliseconds(Int64.Parse(date));

More info: http://blogs.msdn.com/b/marcelolr/archive/2008/03/05/system-datetime-ticks-vs-json-date.aspx

By : Jeremy


Finishing what you posted, AND making it private seemed to work fine for me.

[DataContract]
public class TestClass
{

    private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    [IgnoreDataMember]
    public DateTime MyDateTime { get; set; }

    [DataMember(Name = "MyDateTime")]
    private int MyDateTimeTicks
    {
        get { return (int)(this.MyDateTime - unixEpoch).TotalSeconds; }
        set { this.MyDateTime = unixEpoch.AddSeconds(Convert.ToInt32(value)); }
    }

}


This video can help you solving your question :)
By: admin