Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare datetime without millisecond

Tags:

c#

datetime

I need to compare dates in two separate list. Each list is constructed of MyFile Objects. That is a class that I created in order to have specific information about a file such as name, dateModified, extension, etc. The only problem is that a lot of MyFiles objects in my second list (got those from external hard drive) do not have the dateTime stamp (LastWriteTime) till the millisecond. I believe that is the reason why my comparison is not working. For example here is an example of how my comparison is failing: "Why does c# thinks the dates are not equal?" Debug

a and b are MyFile objects and MyFile class contains a property ticks and that is equal to the file.LastWriteTime.Ticks they are not used in the program I just included them for debugging purposes. So after debugging several times I realized that the last 7 digits represent the milliseconds of a file. As a result my ticks property in MyFile now contains 11 significant figures instead than 18 ( note 18-11 = 7). The problem with this is that when I compare the ticks I get strange results when I try to update the ticks property by dividing by 10000000 and then multyplying by 10000000. Since my ticks propery is a long int it will lose the last 7 digits when I divide. I get less 'errors'. But there is some other times when I get something like this: enter image description here

Here we can see that the dates are the same at least till the second. Why is c# thinking its not the same date? Do I have to create my own "Ticks" function? I know I convert dateTime to string then compare it but I want to have the posiblility of knowing if a object a.dateModified is newer than object b.dateModified

like image 796
Tono Nam Avatar asked May 20 '11 15:05

Tono Nam


1 Answers

Try comparing with specific precision:

DateTime a, b;
// fill a and b with the values you need
if (Math.Abs((a-b).TotalSeconds) < 1)
    Console.WriteLine("File doesn't need to be copied");
else
    Console.WriteLine("File needs to be copied");
like image 190
Zruty Avatar answered Oct 21 '22 00:10

Zruty