Y Chan
Y Chan

Reputation: 317

Compare datetime get different result

I need to compare two dates including the seconds. I searched the web and got two methods. One is import Microsoft.VisualBasic dll. The result is not same when it runs the same data. I think C# should do the same thing without import VisualBasic. Can someone point the way to me to made it work in C#?

Thanks in advance.

There is one using Microsoft.VisualBasic

 if (Math.Abs(DateAndTime.DateDiff(DateInterval.Second, 
     Conversions.ToDate(colFilesFound[RuntimeHelpers.GetObjectValue(rw["file_path"])]),
     Conversions.ToDate(rw["last_modified_timestamp"]), 
     FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1)) == 0L)
 {
     unchangedFileNum++;
     Console.WriteLine("unchange");
 }
 else
 {
     modifiedFileNum++;
     Console.WriteLine("change");
 }

There is another method not using Visual.dll:

DateTime fileLastModifiedDate = Conversions.ToDate(colFilesFound[rw["file_path"]]);
DateTime dataLastModifiedDate = Conversions.ToDate(rw["last_modified_timestamp"]);
if (Math.Abs((fileLastModifiedDate - dataLastModifiedDate).TotalSeconds) == 0L)
{
     Console.WriteLine("File Date: " + colFilesFound[rw["file_path"]] + 
            " <> Database Date: " + Conversions.ToString(rw["last_modified_timestamp"]));
     unchangedFileNum++;
     Console.WriteLine("unchange");
}
else
{
     modifiedFileNum++;
     Console.WriteLine("change");
}

Upvotes: 2

Views: 141

Answers (2)

Daniel Pe&#241;alba
Daniel Pe&#241;alba

Reputation: 31847

The correct way to compare DateTimes in .NET is using the == operator or calling the DateTime.Compare() method:

    DateTime fileLastModifiedDate = ...;
    DateTime dataLastModifiedDate = ...;

    if (fileLastModifiedDate == dataLastModifiedDate)
    {
       ...
    }

You need to take into account the precission. Sometimes, you cannot have enough precission to consider milliseconds. In this case you need to compare the dates without having into account the milliseconds:

public static bool IsSameDateWithoutMilliseconds(DateTime d1, DateTime d2)
{
    return d1.Subtract(d2).TotalSeconds == 0;
}

Upvotes: 3

coolmine
coolmine

Reputation: 4463

Your problem is probably the milliseconds since those are probably not equal the way you check the DateTimes.

DateTime fileLastModifiedDate = Conversions.ToDate(colFilesFound[rw["file_path"]]);
DateTime dataLastModifiedDate = Conversions.ToDate(rw["last_modified_timestamp"]);

fileLastModifiedDate = fileLastModifiedDate.AddMilliseconds(-fileLastModifiedDate.Millisecond);
dataLastModifiedDate = dataLastModifiedDate.AddMilliseconds(-dataLastModifiedDate.Millisecond);

if (DateTime.Compare(fileLastModifiedDate, dataLastModifiedDate) == 0)
{
    // dates are equal
}
else
{
    // dates are not equal
}

Upvotes: 0

Related Questions