因此,我正在做一些进一步的研究,测试等,并得到一些人的帮助。并且我能够提出以下方法:
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小时前)和无论我将索引更改为什么它都没有给我任何正确的值..我可能做错了什么?
答案 0 :(得分:1)
虽然JSON日期没有标准,但大多数JSON日期都以UTC表示。在ISO 8601之后,时间值末尾的“Z”表示情况如此:
"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并假设它们位于同一时区Kind
,即使不是。更多详情here和here。
<强>更新强>
github如何格式化“最新提交”时间?如果您查看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