Github 上次提交值

Github last commit value

所以我一直在做一些进一步的研究、测试等,并得到了一些人的帮助。并且 iv 能够想出以下方法:

public void GithubLastCommit(string apiLink)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("User-Agent",
                "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

            using (var response = client.GetAsync(apiLink).Result)
            {
                var json = response.Content.ReadAsStringAsync().Result;

                dynamic commits = JArray.Parse(json);
                DateTime lastCommit = commits[0].commit.author.date;
                DateTime now = DateTime.Now;
                int Days = (int)((now - lastCommit).TotalDays);
                int Hours = (int)((now - lastCommit).TotalHours);
                int Minutes = (int)((now - lastCommit).TotalMinutes);
                MessageBox.Show(Hours.ToString());
                if(Hours <=24)
                {
                    MessageBox.Show(Hours.ToString() + "Hours ago");
                }
            }
        }
    }

现在 apiLink 即时发送只是一个随机的 github 我发现要测试这个:https://api.github.com/repos/Homebrew/homebrew/commits 但是我似乎没有得到正确的值(当时是 1 小时前的写作),无论我如何更改索引,它都没有给我任何正确的值..我可能做错了什么?

虽然 JSON 日期没有标准,但大多数 JSON 日期都是用 UTC 表示的。 "Z" 在你的时间值末尾,在 ISO 8601 之后,表示是这样的:

    "date": "2015-04-27T03:58:52Z"

事实上,这就是 what Json.NET expects by default,尽管您可以进行其他配置。因此你需要做:

DateTime now = DateTime.UtcNow;

你的计算应该是正确的。那是因为 DateTime 减法运算符 does not consider whether a DateTime is in local or UTC units and just assumes them to be in the same timezone Kind even if not. More details here and here.

更新

github如何格式化"latest commit"时间?如果查看 homebrew 页面的 HTML 源代码,将会看到这样的时间:

       <span class="css-truncate css-truncate-target"><time datetime="2015-04-27T15:31:05Z" is="time-ago">Apr 27, 2015</time></span>

那么,这个 "time-ago" 是什么东西?如果查看页面的 javascript,会发现:

n.prototype.timeAgo = function () {
var e = (new Date).getTime() - this.date.getTime(),
t = Math.round(e / 1000),
n = Math.round(t / 60),
r = Math.round(n / 60),
i = Math.round(r / 24),
o = Math.round(i / 30),
a = Math.round(o / 12);
return 0 > e ? 'just now' : 10 > t ? 'just now' : 45 > t ? t + ' seconds ago' : 90 > t ? 'a minute ago' : 45 > n ? n + ' minutes ago' : 90 > n ? 'an hour ago' : 24 > r ? r + ' hours ago' : 36 > r ? 'a day ago' : 30 > i ? i + ' days ago' : 45 > i ? 'a month ago' : 12 > o ? o + ' months ago' : 18 > o ? 'a year ago' : a + ' years ago'
},

所以看起来,如果时差大于 36 小时但小于 30 天,它们会四舍五入(可能向上)到最接近的天数。您需要复制此逻辑才能在您的代码中获得类似的结果。因此 3.5990 天将四舍五入为“4 天前”。

我在这里找到了相同逻辑的另一个版本:github/time-elements