Ignore milliseconds when comparing two datetimes

前端 未结 14 2159
一个人的身影
一个人的身影 2020-12-08 12:47

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 download

相关标签:
14条回答
  • 2020-12-08 13:25

    The most straightforward way to truncate time is to format it and parse on the units that you want:

    var myDate = DateTime.Parse(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));
    

    DOK's method re-written

    public bool CompareByModifiedDate(string strOrigFile, string strDownloadedFile)
        {
             DateTime dtOrig = DateTime.Parse(File.GetLastWriteTime(strOrigFile).ToString("MM/dd/yyyy hh:mm:ss"));
             DateTime dtNew = DateTime.Parse(File.GetLastWriteTime(strDownloadedFile).ToString("MM/dd/yyyy hh:mm:ss"));
    
             if (dtOrig == dtNew)
                return true;
             else
                return false;
        }
    
    0 讨论(0)
  • 2020-12-08 13:25

    Don't know why almost all programmers needs extra lines to return a bool value from a function with a bool expression.

    instead

    if (dtOrig.ZeroMilliseconds() == dtNew.ZeroMilliseconds())
        return true;
     else
        return false;
    

    you can always just use

    return dtOrig.ZeroMilliseconds() == dtNew.ZeroMilliseconds()
    

    if the expression is true it returns true else false.

    0 讨论(0)
  • 2020-12-08 13:26

    You can subtract them, to get a TimeSpan.

    Then use TimeSpan.totalSeconds()

    0 讨论(0)
  • 2020-12-08 13:28

    You could create an extension method that would set the milliseconds to zero for a DateTime object

    public static DateTime ZeroMilliseconds(this DateTime value) {
      return new DateTime(value.Year, value.Month, value.Day, 
        value.Hours, value.Minutes, value.Seconds);
    }
    

    Then in your function

     if (dtOrig.ZeroMilliseconds() == dtNew.ZeroMilliseconds())
            return true;
         else
            return false;
    
    0 讨论(0)
  • 2020-12-08 13:29

    One way would be to create new dates, inputting the year, month, day, hour, minute, second into the constructor. Alternatively, you could simply compare each value separately.

    0 讨论(0)
  • 2020-12-08 13:33

    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())
    
    0 讨论(0)
提交回复
热议问题