日期时间比较无毫秒 [英] Compare datetime without millisecond

查看:183
本文介绍了日期时间比较无毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在两个单独的列表进行比较的日期。每个列表构造MyFile的对象。这就是我为了创建有一个文件,如特定信息的类名,dateModified,扩展等。唯一的问题是,很多MYFILES在我的第二个对象列表(得到了那些从外部硬盘驱动器)不有日期时间戳(LastWriteTime)直到毫秒。我相信这是为什么我的比较是不工作的原因。例如,这里是我比较失败怎样的一个例子:为什么C#认为日期是不相等的?

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

a和b是MyFile的对象和MyFile的类包含一个属性蜱等于他们没有在我刚刚其中包括用于调试的程序所使用的file.LastWriteTime.Ticks。所以,调试了几次后,我意识到,在过去的7个数字代表文件的毫秒。其结果是我在MyFile的蜱属性现在包含11显著数字代替超过18(注意18-11 = 7)。这样做的问题是,当我比较蜱我得到奇怪的结果,当我尝试通过千万分更新蜱属性,然后通过10000000 multyplying由于我的蜱属性为long int类型时,我就会失去最后7位数划分。我得到较少的错误。但有一些其他的时候,我得到这样的:

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:

下面,我们可以看到,日期是相同的,至少直到第二。为什么C#的思维不一样的日期?我一定要建立自己的滴答功能?我知道我日期时间转换为字符串,然后比较,但我希望有知道如果一个对象a.dateModified
的posiblility比对象b.dateModified

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

这篇关于日期时间比较无毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆