开发者

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开发者_JS百科.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
{
     ...
}


You need to use lastMod.Equals(file.CreatedOn) assuming that the times are actually equal


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜