【问题标题】:How to compare to this date in C#?如何在 C# 中与这个日期进行比较?
【发布时间】:2016-08-11 17:45:23
【问题描述】:

下面是我从 REST API 获得的到 Sonatype Nexus 的字符串。因为我想删除超过 60 天的任何内容。如何用 C# 编写这段代码?

<lastModified>2016-08-11 14:12:26.37 UTC</lastModified>

【问题讨论】:

标签: c# datetime


【解决方案1】:

假设您的 API 将始终返回 &lt;lastModified&gt;&lt;/lastModified&gt; .. 以下将执行您想要的操作。

var MyString = "<lastModified>2016-08-11 14:12:26.37 UTC</lastModified>";
MyString = MyString.Substring(14);
MyString = MyString.Replace("UTC", "");
MyString = MyString.Substring(0, MyString.Length - 15);

DateTime MyDateTime = new DateTime();
DateTime.TryParse(MyString, out MyDateTime);

if (MyDateTime < DateTime.Now.AddDays(-60) && MyDateTime != new DateTime(0001, 1, 1))
{
    //Do  Your Code
}

【讨论】:

  • 我不会使用Substring,而是使用Replace 来删除标签:MyString.Replace("&lt;lastmodified&gt;", string.Empty); 魔术数字是我的敌人。
  • 子字符串解决了我的另一个问题。我正在使用“yyyy-MM-dd HH:mm:ss.fff UTC”进行解析,但有时发现返回字符串有时以 ff 或 f 结尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
相关资源
最近更新 更多