【问题标题】:Compare DateTime to date stored in database将 DateTime 与存储在数据库中的日期进行比较
【发布时间】:2011-07-15 02:45:32
【问题描述】:

我有两个约会时间。 我从 sql server 获取的一个日期时间,另一个日期是客户端的日期时间。

两个日期时间相等,但在我的代码中返回不相等。 为什么?

var mngProduct = new ProductManager();
var file = mngProduct.GetProductImageData(int.Parse(context.Request["imageId"]), imageSize);

if (!String.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]))
{
  System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
  var lastMod = DateTime.ParseExact(context.Request.Headers["If-Modified-Since"], "r", provider).ToLocalTime();
  if (lastMod==file.CreatedOn)//return false always
  {
    res.StatusCode = 304;
    res.StatusDescription = "Not Modified";
    return;
  }
}
res.ContentType = file.MimeType;
res.AddHeader("Content-disposition", "attachment; filename=" + file.FileName);
res.AddHeader("Content-Length", file.Content.Length.ToString());
res.BinaryWrite(file.Content.ToArray());
res.Cache.SetCacheability(HttpCacheability.Public);
res.Cache.SetLastModified(file.CreatedOn);

【问题讨论】:

  • 您确定要比较同一时区设置中的日期时间值吗?

标签: c# .net sql-server datetime


【解决方案1】:

SQL DateTime 在毫秒方面的精度较低。我会检查两个日期的差异是否小于一个小的TimeSpan

if(Math.Abs(date1.Subtract(date2).TotalSeconds)>1) // difference of more than 1 second
{
     ...
}

【讨论】:

    【解决方案2】:

    你需要使用lastMod.Equals(file.CreatedOn) 假设时间实际上是相等的

    【讨论】:

      【解决方案3】:

      我想它们并不完全相同。日期分量可能相等,但时间分量可能不相等,或者时间分量可能相差几毫秒,这将导致运算符返回 false。

      您是否检查过调试器中的实际值以确保它们确实完全相同相同?

      如果您只对比较实际日期感兴趣,您可能需要考虑以下内容:

      if(lastMod.Year != file.Year || lastMod.Month!= file.Month || lastMod.Month != file.Month)
      {
         ....
      }
      

      您可以使用DateTime 结构的其他类似属性来仅比较您真正感兴趣的部分。

      【讨论】:

        【解决方案4】:

        您确定 2 个日期时间相同吗?两者必须具有相同的毫秒数(Ticks)。

        我建议您获取这 2 之间的 TimeSpan 并测试跨度是否小于一秒、一分钟或您认为合适的任何值。

        如果您只需要比较日期时间的日期部分。比较日期时间的Date 属性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-20
          • 1970-01-01
          • 2020-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多