简体   繁体   English

比较datetime而不是毫秒

[英]Compare datetime without millisecond

I need to compare dates in two separate list. 我需要在两个单独的列表中比较日期。 Each list is constructed of MyFile Objects. 每个列表都由MyFile对象构成。 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. 这是我创建的一个类,用于获取有关文件的特定信息,例如name,dateModified,extension等。唯一的问题是我的第二个列表中的很多MyFiles对象(从外部硬盘驱动器获取)没有将dateTime标记(LastWriteTime)保留到毫秒。 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?" 例如,这里是我的比较失败的一个例子:“为什么c#认为日期不相等?” 调试

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. a和b是MyFile对象,MyFile类包含一个属性ticks,它等于file.LastWriteTime.Ticks它们没有在我刚刚包含它们的程序中用于调试目的。 So after debugging several times I realized that the last 7 digits represent the milliseconds of a file. 因此,经过多次调试后,我意识到最后7位代表文件的毫秒数。 As a result my ticks property in MyFile now contains 11 significant figures instead than 18 ( note 18-11 = 7). 因此,我在MyFile中的ticks属性现在包含11个有效数字而不是18个(注意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. 这个问题是,当我比较滴答时,当我尝试通过除以10000000然后多打10000000来更新ticks属性时,我得到奇怪的结果。因为我的ticks propery是一个long int,它将丢失最后7位数当我划分。 I get less 'errors'. 我得到的'错误'更少。 But there is some other times when I get something like this: 但是有一些其他时候我得到这样的东西: 在此输入图像描述

Here we can see that the dates are the same at least till the second. 在这里我们可以看到日期至少相同,直到第二个。 Why is c# thinking its not the same date? 为什么c#认为它不是同一个日期? Do I have to create my own "Ticks" function? 我是否必须创建自己的“Ticks”功能? 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 我知道我将dateTime转换为字符串然后比较它但我希望知道对象a.dateModified是否比对象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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM