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

被刻印的时光 ゝ 提交于 2019-11-30 03:19:24

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

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

Here's what I've come up with. In C#, it looks like you need to create a new DateTime and add the epoch value as 'seconds' to this DateTime. Here's what it looks like in code:

new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(1221818565);

When using the Visual Studio immediate window, I printed the result of this operation to the debugger console:

{9/19/2008 10:02:45 AM}
    Date: {9/19/2008 12:00:00 AM}
    Day: 19
    DayOfWeek: Friday
    DayOfYear: 263
    Hour: 10
    Kind: Unspecified
    Millisecond: 0
    Minute: 2
    Month: 9
    Second: 45
    Ticks: 633574153650000000
    TimeOfDay: {10:02:45}
    Year: 2008

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

What you want is the following:

DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime dotnetTime = unixEpoch.AddSeconds(Convert.ToDouble(ticks));

where ticks is the value passed to you by PHP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!