简体   繁体   中英

Compare DateTime to date stored in database

I have two datetimes. One datetime I get from a sql server and the other date is the client's datetime.

The two datetimes are equal but in my code return not equal. Why?

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

SQL DateTime has less precision when it comes to milliseconds. I would check to see if the diff of two dates are less than a small TimeSpan .

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

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

I would imagine they are not exactly the same. The date components may be equal, but possibly the time components are not, or the time component could be off by milliseconds, which would cause the operator to return false.

Have you inspected the actual values in the debugger to ensure they are indeed exactly the same?

If you are only interested in comparing the actual date, you might want to consider something like:

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

You can use other similar properties of the DateTime structure to compare just the parts you are actually interested in.

Are you sure the 2 datetime are the same? Both must have the same millisecond (Ticks).

I suggest you to get the TimeSpan between this 2 and test if the span is less that a second, a minute or any that you think is good.

If you only need to compare the date part of the datetime. Compare the Date properties of the datetime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM