比较date时混乱

比较date时遇到问题:

Sub Main() Dim xlApp, xlApp1, xlApp2 As Excel.Application Dim xlWorkBook, xlWorkBook1, xlWorkBook2 As Excel.Workbook Dim xlWorkSheet, xlWorkSheet1, xlWorkSheet2 As Excel.Worksheet Dim folder, m, n As String Dim subfolders As String() Dim i, j, c, k, l, lastrow As Integer Dim fec,temp As Date Dim nulls As Boolean nulos = False folder = My.Application.Info.DirectoryPath ChDir(CurDir()) subfolders = IO.Directory.GetDirectories(CurDir()) xlApp = New Excel.ApplicationClass xlApp2 = New Excel.ApplicationClass xlApp1 = New Excel.ApplicationClass Try xlWorkBook = xlApp.Workbooks.Open("d:\File where data will be copied.xlsx") xlWorkSheet = xlWorkBook.Worksheets("SheetName") xlWorkSheet.Activate() xlWorkBook2 = xlApp2.Workbooks.Open("d:\File Where Dates Are Recorded.xlsx") xlWorkSheet2 = xlWorkBook2.Worksheets("SheetName") xlWorkSheet2.Activate() i = 2 For Each f1 In subfolders ChDir(f1) m = Dir("*.xlsx") Do While m <> "" If Strings.Left(m, 6) = "DOC_ID" Then j = 2 Do While xlWorkSheet2.Cells(j, 1).Value <> "" If xlWorkSheet2.Cells(j, 1).Value = m Then fec = xlWorkSheet2.Cells(j, 2).value 'Check if last write date is the same as the one recorded in the file temp = File.GetLastWriteTime(CurDir() & "\" & m) If fec <> File.GetLastWriteTime(CurDir() & "\" & m) Then . . . 

在最后一行

 If fec <> File.GetLastWriteTime(CurDir() & "\" & m) 

我将文件的修改date与存储在工作表单元格中的date作为date格式进行比较。 debugging时,fec和temp具有相同的值(已经在debugging器中testing过),但是它仍然进入if条件内…为什么? 有任何想法吗?

本地窗口中的值:

fec#11/15/2013 6:06:01 PM#

temp#11/15/2013 6:06:01 PM#

=<>基本上只是比较DateTime.Ticks 。 您可能要输出fec.TicksFile.GetLastWriteTime(...).Ticks出于debugging目的。 毫秒等于10000个滴答声。

如果他们不同的整整一个小时的倍数,你可能想检查DateTime.Kind 。 一个是UTC,另一个是你当地的时区。 如果是这样,你需要弥补差异。

尝试使用此代码,而不是:

 if DateTime.Compare(fec, temp) <> 0 then 

比较某些值(如string和date)通常比使用'='运算符使用与数据types相关联的内置函数效果更好。 另请参阅: http : //msdn.microsoft.com/zh-CN/library/system.datetime.compare(v=vs.110).aspx