Convert unix timestamp to normal date (UWP)

戏子无情 提交于 2019-12-13 02:55:50

问题


I have UWP app where I get my json , write list and Binf to View

Here is code of View Model:

 public class TopPostsViewModel : INotifyPropertyChanged
{
    private List<Child> postsList;

    public List<Child> PostsList
    {
        get { return postsList; }
        set { postsList = value; OnPropertyChanged(); }
    }

    public TopPostsViewModel()
    {
        Posts_download();
    }


    public async void Posts_download()
    {
        string url = "https://www.reddit.com/top/.json?count=50";

        var json = await FetchAsync(url);


        RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);
        PostsList = new List<Child>(rootObjectData.data.children);

    }
    private async Task<string> FetchAsync(string url)
    {
        string jsonString;

        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        return jsonString;
    }

In json I have data.created_utc field. For example it's like this created_utc: 1446179731. I read that this is unix timestamp

Here is my classes: Classes

I need to convert it to normal date. How I can do this and write to List back?

So my question is more about, how to take field and write it back.


回答1:


You will have to add another property in Data2 class to get the converted data in DateTime.

    [JsonIgnore]
    public DateTime created_utc
    {
        get
        {
            var unix = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return unix.AddSeconds(this.created_utcUnix);
        }
        set
        {
            var unix = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            this.created_utcUnix = Convert.ToInt64((value - unix).TotalSeconds);
        }
    }

    [JsonProperty("created_utc")]
    public double created_utcUnix { get; set; }

Now you can always use created_utcCustom in your client code

New Code : https://pastebin.com/A4GReYHj




回答2:


While @saurabh have a good way. But I think you may want to convert it and dont change the class.

You can use JsonConverter to convert it.

public class Data2
{
   [JsonConverter(typeof(UnixConvert))]
   public DateTime created_utc{set;get;}
}

I have a foo class. The foo class have a property which name is created_utc.

    class Foo
    {
        [JsonConverter(typeof(UnixConvert))]
        public DateTime created_utc { set; get; }
    }

UnixConvert is a JsonConverter

    class UnixConvert : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var time = ToUnixTimestamp((DateTime) value);
            writer.WriteValue(time);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long unixTimeStamp = long.Parse(reader.Value.ToString());
            return UnixTimeStampToDateTime(unixTimeStamp);
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
        {
            System.DateTime dtDateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
            return dtDateTime;
        }

        public static long ToUnixTimestamp(DateTime time)
        {
            var date = new DateTime(1970, 1, 1, 0, 0, 0, time.Kind);
            var unixTimestamp = System.Convert.ToInt64((time - date).TotalSeconds);

            return unixTimestamp;
        }
    }

I write a test code:

        Foo foo = new Foo()
        {
            created_utc = DateTime.Now
        };
        var str = JsonConvert.SerializeObject(foo);
        foo = JsonConvert.DeserializeObject<Foo>(str);

I can see it can run.

See https://stackoverflow.com/a/28305303/6116637



来源:https://stackoverflow.com/questions/44643498/convert-unix-timestamp-to-normal-date-uwp

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