比较日期时的困惑

时间:2013-11-25 15:55:27

标签: vb.net excel visual-studio 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)

我将文件的修改日期与工作表单元格中存储的日期作为日期格式进行比较。 调试时,fec和temp具有相同的值(已经在调试器中测试过)但它仍然进入if条件...为什么?有什么想法吗?

本地化窗口中的值:

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

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

2 个答案:

答案 0 :(得分:2)

请尝试使用此代码:

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

比较某些值(例如字符串和日期)通常使用与数据类型相关联的内置函数比使用&#39; =&#39;更好。运营商。另见:http://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx

答案 1 :(得分:2)

=<>基本上只是比较DateTime.Ticks。您可能希望输出fec.TicksFile.GetLastWriteTime(...).Ticks以进行调试。毫秒等于10,000个滴答。

如果它们相差一整小时,您可能需要检查DateTime.Kind。可能是一个是UTC,另一个是你当地的时区。如果是这种情况,您需要补偿差异。

相关问题