Ignore milliseconds when comparing two datetimes

58,133

Solution 1

Create a new DateTime value with the milliseconds component set to 0:

dt = dt.AddMilliseconds(-dt.Millisecond);

Solution 2

I recommend you use an extension method:

public static DateTime TrimMilliseconds(this DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0, dt.Kind);
}

then its just:

if (dtOrig.TrimMilliseconds() == dtNew.TrimMilliseconds())

Solution 3

Care should be taken, if dt has non-zero microseconds (fractions of millis). Setting only milliseconds to zero is not enough.
To set millis and below to zero (and get a succesfull comparison), the code would be:

dt = dt.AddTicks(-dt.Ticks % TimeSpan.TicksPerSecond); // TimeSpan.TicksPerSecond=10000000

Solution 4

TimeSpan difference = dtNew - dtOrig;
if (difference >= TimeSpan.FromSeconds(1))
{
    ...
}

Solution 5

You can subtract them, to get a TimeSpan.

Then use TimeSpan.totalSeconds()

Share:
58,133
Admin
Author by

Admin

Updated on October 16, 2021

Comments

  • Admin
    Admin over 2 years

    This is probably a dumb question, but I cannot seem to figure it out. I am comparing the LastWriteTime of two files, however it is always failing because the file I downloaded off the net always has milliseconds set at 0, and my original file has an actual value. Is there a simple way to ignore the milliseconds when comparing?

    Here's my function:

    //compare file's dates
    public bool CompareByModifiedDate(string strOrigFile, string strDownloadedFile)
    {
         DateTime dtOrig = File.GetLastWriteTime(strOrigFile);
         DateTime dtNew = File.GetLastWriteTime(strDownloadedFile);
    
         if (dtOrig == dtNew)
            return true;
         else
            return false;
    }
    

    Thanks in advance

  • Ash Burlaczenko
    Ash Burlaczenko almost 13 years
    So your method returns a DateTime but is defined as returning a string.
  • TheCloudlessSky
    TheCloudlessSky over 10 years
    Warning: this won't work when the DateTime has non-zero microseconds. See @PeterIvan's or @DeanChalk's answers.
  • Mickey Mouse
    Mickey Mouse over 9 years
    I don't know why all programmers needs too many lines when rteurning a bool function with
  • Luke Hutton
    Luke Hutton over 9 years
    Perhaps preserve the DateTimeKind as well by adding dt.Kind to end of ctor
  • Purusartha
    Purusartha over 9 years
    where did you get ZeroMilliseconds() from?
  • Adamy
    Adamy almost 9 years
    return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0, dt.Kind);
  • Simon MᶜKenzie
    Simon MᶜKenzie over 8 years
    Run your code in the UK, Europe or Australia and see what happens. I'm not a fan of this approact anyway, but you need to be using an invariant culture or DateTime.ParseExact for this to be even remotely reliable.
  • Larry
    Larry over 8 years
    This is the way to go IMHO.
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 8 years
    This is the best solution. Fast, and preserves dt.Kind. I know it gives the same in all cases, but to me it is more natural to use dt = dt.AddTicks(-(dt.Ticks % TimeSpan.TicksPerSecond));, i.e. use % operator first, and then negate. That is because the behavior of % with a negative first operand seems a bit confusing to me, so I prefer my version where % operates on two positive operands.
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 8 years
    With Peter Ivan's solution, it is natural to just do public static DateTime TruncateTo(this DateTime dt, long truncateResolution) { return dt.AddTicks(-(dt.Ticks % truncateResolution)); }. Much shorter and clearer. Then use like this: DateTime dtSecs = DateTime.Now.TruncateTo(TimeSpan.TicksPerSecond); DateTime dtHrs = DateTime.Now.TruncateTo(TimeSpan.TicksPerHour); and so on. You can even truncate to more strange resolutions, like multiples of 3 hours (3 * TimeSpan.TicksPerHour).
  • Peter Ivan
    Peter Ivan almost 8 years
    @JeppeStigNielsen: Your code is exactly the same as mine. According to operator precedence, you multiply and/or divide and just then add/negate. So the parentheses change nothing, just clarify the well-established logic.
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen almost 8 years
    No that is incorrect. In rare cases (that cannot occur in your use above, so your use is fine), there is a difference. Consider this code (where a and b must not be declared const): long a = long.MinValue; long b = 10L; long x = (-a) % b; long y = -(a % b); long z = -a % b; Here the value of x will be negative, because negation of a gives a again, and a negative value %-ed on a positive value gives a negative value. But the value of y is positive, because this time we negate a negative result between -10 and 0, and that gives a positive number. Now check z to see it!
  • Doug Domeny
    Doug Domeny almost 4 years
    The dt.Kind should be set for each new DateTime
  • Doug Domeny
    Doug Domeny almost 4 years
    The value.Kind should be set in new DateTime