将 unix 时间戳转换为正常日期 (UWP) [英] Convert unix timestamp to normal date (UWP)

查看:66
本文介绍了将 unix 时间戳转换为正常日期 (UWP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 UWP 应用程序,我可以在其中获取 json、写入列表和要查看的 Binf

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

这是视图模型的代码:

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

在 json 中,我有 data.created_utc 字段.例如它就像这样 created_utc: 1446179731.我读到这是 unix 时间戳

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

这是我的课程:课程

我需要将其转换为正常日期.我如何才能做到这一点并写回 List?

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.

推荐答案

您必须在 Data2 类中添加另一个属性才能在 DateTime 中获取转换后的数据.

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

现在您始终可以在客户端代码中使用 created_utcCustom

Now you can always use created_utcCustom in your client code

新代码:https://pastebin.com/A4GReYHj

这篇关于将 unix 时间戳转换为正常日期 (UWP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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