Compare DateTime to date stored in the database

I have two times. One day I get from sql server and another date is the date and time of the client.

Two days of life are equal, but they are not equal in my return code. 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);
+3
source share
4 answers

SQL DateTimehas less precision when it comes to milliseconds. I would see if the difference between the two dates is not small TimeSpan.

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

You need to use lastMod.Equals(file.CreatedOn), assuming that time is actually equal

+1
source

, . , , , , , , false.

, , ?

, - :

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

You can use other similar structure properties DateTimeto compare only those parts that really interest you.

+1
source

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

I suggest you get a TimeSpan between this 2 and check if there is less gap, second, minute or something that you think is good.

If you need to compare only the date in the date. Compare the properties of Datedatetime.

+1
source

All Articles