比较datetime没有毫秒 [英] Compare datetime without millisecond

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

问题描述

我需要在两个单独的列表中比较日期。每个列表由MyFile对象构成。这是我创建的一个类,以便具有关于诸如name,dateModified,extension等的文件的具体信息。唯一的问题是我的第二个列表中的很多MyFiles对象(从外部硬盘驱动器获取)将dateTime戳记(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类包含一个属性ticks,等于file.LastWriteTime.Ticks,它们在程序中没有使用,我只是将它们包含进来进行调试。所以经过调试好几次,我意识到最后的7位代表文件的毫秒数。因此,MyFile中的ticks属性现在包含11个有效数字而不是18(注18-11 = 7)。这个问题是,当我比较ticks时,当我尝试通过除以10000000更新ticks属性,然后乘以10000000时,我得到了奇怪的结果。由于我的ticks属性是一个长整型,它会丢失最后的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#认为它的日期不一样?我必须创建自己的Ticks功能吗?我知道我将dateTime转换成字符串,然后比较它,但是我想要知道一个对象a.dateModified
是否比对象b.dateModified更新的posiblility

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

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

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