开发者

Compare datetime without millisecond

开发者 https://www.devze.com 2023-03-07 19:50 出处:网络
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,

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?"

Compare datetime without millisecond

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:

Compare datetime without millisecond

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


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消