如何从日期时间JSON转换为C#? [英] How to convert DateTime from JSON to C#?

查看:217
本文介绍了如何从日期时间JSON转换为C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
如何UNIX时间戳转换为日期时间,反之亦然?

我有以下类:

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



这里的JSON:

Here's the JSON:

{ "MyDateTime":"1221818565" }

的JSON正在从一个PHP Web服务返回。

The JSON is being returned from a PHP webservice.

我需要做的,是那个时代的字符串转换成有效的C#日期时间。什么是这样做的最好办法

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

我可以这样做:

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

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



但与此麻烦的是,MyDateTimeTicks是公共的(将其更改为私人原因在序列化过程中的异常)

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

推荐答案

完成你发布什么,并使其私人似乎为我工作的罚款。

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

}

这篇关于如何从日期时间JSON转换为C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆