DateTime.Parse是否与VB6完全等效?

DateTime.Parse是否与VB6完全等效?,datetime,vb6,Datetime,Vb6,有人知道VB6中是否有一个与.NET的DateTime.ParseExact()方法等效的方法吗?我尝试过使用DateSerial()、IsDate()和CDate(),但是,由于VB6的所有“帮助”,我得到了一些意想不到的结果 更具体地说,我试图从用户输入中解析一个文本字符串,以验证它是否为实际日期。例如,我将使用日期8/25/16。通常的预期输入在月、日和年之间可能有分隔符,也可能没有分隔符,因此可以将其输入为82516 下面是一个无法正常工作的代码示例(82516的值存储在TempStr变

有人知道VB6中是否有一个与.NET的
DateTime.ParseExact()
方法等效的方法吗?我尝试过使用
DateSerial()
IsDate()
CDate()
,但是,由于VB6的所有“帮助”,我得到了一些意想不到的结果

更具体地说,我试图从用户输入中解析一个文本字符串,以验证它是否为实际日期。例如,我将使用日期
8/25/16
。通常的预期输入在月、日和年之间可能有分隔符,也可能没有分隔符,因此可以将其输入为
82516

下面是一个无法正常工作的代码示例(
82516
的值存储在
TempStr
变量中):

使用指定的值,触发第一个条件。知道它是如何工作的,我理解它发生的原因(它“重新安排”月、日和年,试图匹配一个有效的日期),但我真的试图让它以特定的顺序解析日期。我知道.NET的
DateTime.ParseExact()
方法可以让我达到目的,但我必须在VB6中实现这一点(维护一些遗留代码)

我尝试使用
DateSerial()

但如果任何参数的值超出可接受的范围,也会自动进行校正

我还尝试了上述代码的以下变体:

If IsDate(Format(TempStr, "m/dd/yy")) And IsDate(Format(TempStr, "mm/d/yy")) Then
...
但是第一次测试的结果是完全不同的
3/12/26
,这与原始输入相差很远


有没有办法准确地模拟VB6中的.NET
DateTime.ParseExact()
方法,还是我必须将这些类型的用户输入值作为无效/不明确的值扔掉?

我将亲自编写一个函数,以确保返回正确的日期-

首先获取字符串/整数,将其分解为多个块,并向这些块添加值,然后返回一个组合日期

Option Explicit

Public Function MakeCorrectDate()

Dim xMakeDate As Long, xDay As Integer, xMonth As Integer, xYear As Integer, xCentury As Integer, strCorrectDate As String
''xMake as long because of size, strCorrectDate as string to allow the /...

xMakeDate = txtInput.Text

''Assuming the format will ALWAYS be the same days, months and year (12/20/16) and length is ALWAYS 6...
xDay = Left$(xMakeDate, 2)
xMonth = Mid$(xMakeDate, 3, 2)
xYear = Right(xMakeDate, 2)

''First get the correct part to 1900 or 2000...
If xYear = "00" Then
    xCentury = 20
ElseIf xYear < 99 And xYear > 20 Then ''Year 2000 and year 2020
    xCentury = 19
        Else
    xCentury = 20
End If

strCorrectDate = xDay & "/" & xMonth & "/" & xCentury & xYear

txtYear.Text = strCorrectDate

End Function

Private Sub cmdGetCorrectDate_Click()

If Not Len(txtInput.Text) = 6 Then
    MsgBox "Incorrect information, must be 6 or more characters."

    Exit Sub
        Else
    Call MakeCorrectDate
End If
End Sub

Private Sub txtInput_Change()

''Ensure the user adds only numerical text...
Dim WshShell As Object

Set WshShell = CreateObject("WScript.Shell")

If Not IsNumeric(txtInput.Text) Then
    WshShell.SendKeys "{BackSpace}"
End If
End Sub
选项显式
公共函数makecorrectordate()
Dim xMakeDate为长,xDay为整数,xMonth为整数,xYear为整数,xCentury为整数,strCorrectDate为字符串
''xMake as long因为大小,strCorrectDate作为字符串以允许/。。。
xMakeDate=txtInput.Text
“假设格式总是相同的天、月和年(12/20/16),长度总是6。。。
xDay=Left$(xMakeDate,2)
xMonth=Mid$(xMakeDate,3,2)
xYear=Right(xMakeDate,2)
''首先将正确的部分设置为1900或2000。。。
如果xYear=“00”,则
xCentury=20
如果xYear<99且xYear>20,则“2000年和2020年”
xCentury=19
其他的
xCentury=20
如果结束
strCorrectDate=xDay&“/”&xMonth&“/”&xCentury&xYear
txtYear.Text=strCorrectDate
端函数
私有子cmdGetCorrectDate_Click()
如果不是Len(txtInput.Text)=6,则
MsgBox“信息不正确,必须为6个或更多字符。”
出口接头
其他的
调用MakeCorrectDate
如果结束
端接头
专用子txtInput_Change()
''确保用户只添加数字文本。。。
将WshShell设置为对象
设置WshShell=CreateObject(“WScript.Shell”)
如果不是数字(txtInput.Text),则
WshShell.SendKeys“{BackSpace}”
如果结束
端接头

好的,下面是我为满足当前需求而提出的解决方案。与上面@Andre Oosthuizen发布的内容类似,我决定从以前的工作中大幅简化验证。这一系列功能要求用户输入六位数的日期(两位数的月、两位数的日和两位数的年)。我不相信世纪会成为这个特定应用程序中的一个因素,所以我将省略这个测试

这应该是我们的用户可以接受的,因为他们在其他系统中也有类似的限制。虽然我个人更喜欢一个“防弹”的解决方案(比如使用
日期选择器
或其他UI操作),但我认为这对我们的环境来说是最有效的

'----------------------------------------------------------------------
' LostFocus event handler for the txtEffectiveDate TextBox.
' Test for a valid date when the user attempts to leave the field.
'----------------------------------------------------------------------
Private Sub txtEffectiveDate_LostFocus()
    ' *********************************************************************
    ' ** Don't have the event handler try to do any parsing.  Just pass  **
    ' ** the .Text value to the validation function.  If a date comes    **
    ' ** back, reformat it to "look" like a date and move on.  Otherwise **
    ' ** pop up an "error" message and return focus to the TextBox for   **
    ' ** the user to correct their input.                                **
    ' *********************************************************************
    Dim TempDate As Date

    TempDate = CheckForValidDate(Me.txtEffectiveDate.Text)

    If TempDate > #12:00:00 AM# Then
        ' If a valid Date is returned, put the formatted String value
        ' into the TextBox and move on.
        Me.txtEffectiveDate.Text = Format(TempDate, "mm/dd/yy")
    Else
        ' If the Date value is not valid (#12:00:00 AM#), notify the
        ' user and refocus on the TextBox to force the user to
        ' correct the input before continuing.
        MsgBox "The date you entered was not valid." & vbCrLf & vbCrLf & _
               "Please enter two digits for the month, two digits for the day and" & vbCrLf & _
               "two digits for the year." & vbCrLf & vbCrLf & _
               "For example, today's date should be entered as either " & Format(Now, "mmddyy") & vbCrLf & _
               " or " & Format(Now, "mm/dd/yy") & ".", _
               vbOKOnly + vbExclamation, "INVALID INPUT FORMAT"
        Me.txtEffectiveDate.SetFocus
        Me.txtEffectiveDate.SelStart = 0
        Me.txtEffectiveDate.SelLength = Len(Me.txtEffectiveDate.Text)
    End If
End Sub

'----------------------------------------------------------------------
' Attempts to convert the String input to a Date value.  If the String
' value is already a Date (i.e., "1/1/16" or similar), go ahead and
' assume that the user wants that date and return it as a Date value.
' Otherwise, strip any non-numeric characters and break apart the input
' to pass along for further validation.
'----------------------------------------------------------------------
Private Function CheckForValidDate(ByVal DateStr As String) As Date
    Dim TempDate As Date

    If IsDate(DateStr) Then
        ' If the String value is already in a date format, 
        ' just return the Date value of the String.
        TempDate = CDate(DateStr)
    Else
        Dim TempStr As String
        Dim CurrentChar As String
        Dim TempYear As Integer
        Dim TempMonth As Integer
        Dim TempDay As Integer
        Dim I As Integer

        ' Strip all non-numeric characters to get a purely numeric string.
        For I = 1 To Len(DateStr)
            CurrentChar = Mid(DateStr, I, 1)

            If IsNumeric(CurrentChar) Then
                TempStr = TempStr & CurrentChar
            End If
        Next I

        ' The all-numeric string should be exactly six characters
        ' (for this application).
        If Len(Trim(TempStr)) = 6 Then
            Dim NewDateStr As String

            ' Break the numeric string into the component parts -
            ' Month, Day, and Year.  At six characters, there should
            ' be two characters for each element.
            TempMonth = CInt(Left(TempStr, 2))
            TempDay = CInt(Mid(TempStr, 3, 2))
            TempYear = CInt(Right(TempStr, 2))

            ' Now pass the individual values to the second part of
            ' the validation to ensure each of the individual values
            ' falls within acceptable ranges.
            NewDateStr = GetValidDateString(TempMonth, TempDay, TempYear)

            ' If the returned String value is not empty, then convert
            ' it to a Date value for returning to the calling method
            If Len(Trim(NewDateStr)) > 0 Then
                TempDate = CDate(NewDateStr)
            End If
        End If
    End If

    CheckForValidDate = TempDate
End Function

'----------------------------------------------------------------------
' Using numeric values for Month, Day, and Year, attempt to build a
' valid Date in mm/dd/yy format.
'----------------------------------------------------------------------
Private Function GetValidDateString(ByVal intMonth As Integer, ByVal intDay As Integer, ByVal intYear As Integer) As String
    Dim ReturnStr As String

    ReturnStr = ""

    If intMonth >= 1 And intMonth <= 12 Then
        Select Case intMonth
            Case 1, 3, 5, 7, 8, 10, 12
                ' January, March, May, July, August, October and December
                ' have 31 days.
                If intDay >= 1 And intDay <= 31 Then
                    ReturnStr = intMonth & "/" & intDay & "/" & intYear
                End If
            Case 4, 6, 9, 11
                ' April, June, September and November
                ' have 30 days
                If intDay >= 1 And intDay <= 30 Then
                    ReturnStr = intMonth & "/" & intDay & "/" & intYear
                End If
            Case 2
                ' Depending on whether it is a Leap Year (every four years),
                ' February may have 28 or 29 days.
                If intYear Mod 4 = 0 Then
                    If intDay >= 1 And intDay <= 29 Then
                        ReturnStr = intMonth & "/" & intDay & "/" & intYear
                    End If
                Else
                    If intDay >= 1 And intDay <= 28 Then
                        ReturnStr = intMonth & "/" & intDay & "/" & intYear
                    End If
                End If
        End Select
    End If

    ' Return the recombined string to the calling function.
    GetValidDateString = ReturnStr
End Function
'----------------------------------------------------------------------
'txtEffectiveDate文本框的LostFocus事件处理程序。
'测试用户试图离开该字段时的有效日期。
'----------------------------------------------------------------------
私有子txtEffectiveDate_LostFocus()
' *********************************************************************
“**不要让事件处理程序尝试进行任何分析。过关**
'**验证函数的.Text值。如果有约会**
“**返回,将其重新格式化为“看起来”像日期,然后继续。否则**
'**弹出一条“错误”消息,并将焦点返回到文本框,以便**
“**允许用户更正其输入**
' *********************************************************************
日期为日期
TempDate=CheckForValidDate(Me.txtEffectiveDate.Text)
如果TempDate>上午12:00:00,则
'如果返回了有效的日期,请输入格式化的字符串值
'进入文本框并继续。
Me.txtEffectiveDate.Text=格式(TempDate,“mm/dd/yy”)
其他的
'如果日期值无效(#12:00:00 AM#),请通知
'用户,并重新聚焦文本框以强制用户
'在继续之前更正输入。
MsgBox“您输入的日期无效。”&vbCrLf&vbCrLf&_
“请输入两位数字表示月份,两位数字表示日期和”&vbCrLf&_
“年度两位数。”&vbCrLf&vbCrLf&_
例如,今天的日期应输入为“&格式(现在为“mmddyy”)&vbCrLf&_
或“&格式(现在为“mm/dd/yy”)&”。”_
vbOKOnly+VBEQUOTION,“输入格式无效”
Me.txtEffectiveDate.SetFocus
Me.txtEffectiveDate.SelStart=0
Me.txtEffectiveDate.SelLength=Len(Me.txtEffectiveDate.Text)
如果结束
端接头
'---------------------------------------
Option Explicit

Public Function MakeCorrectDate()

Dim xMakeDate As Long, xDay As Integer, xMonth As Integer, xYear As Integer, xCentury As Integer, strCorrectDate As String
''xMake as long because of size, strCorrectDate as string to allow the /...

xMakeDate = txtInput.Text

''Assuming the format will ALWAYS be the same days, months and year (12/20/16) and length is ALWAYS 6...
xDay = Left$(xMakeDate, 2)
xMonth = Mid$(xMakeDate, 3, 2)
xYear = Right(xMakeDate, 2)

''First get the correct part to 1900 or 2000...
If xYear = "00" Then
    xCentury = 20
ElseIf xYear < 99 And xYear > 20 Then ''Year 2000 and year 2020
    xCentury = 19
        Else
    xCentury = 20
End If

strCorrectDate = xDay & "/" & xMonth & "/" & xCentury & xYear

txtYear.Text = strCorrectDate

End Function

Private Sub cmdGetCorrectDate_Click()

If Not Len(txtInput.Text) = 6 Then
    MsgBox "Incorrect information, must be 6 or more characters."

    Exit Sub
        Else
    Call MakeCorrectDate
End If
End Sub

Private Sub txtInput_Change()

''Ensure the user adds only numerical text...
Dim WshShell As Object

Set WshShell = CreateObject("WScript.Shell")

If Not IsNumeric(txtInput.Text) Then
    WshShell.SendKeys "{BackSpace}"
End If
End Sub
'----------------------------------------------------------------------
' LostFocus event handler for the txtEffectiveDate TextBox.
' Test for a valid date when the user attempts to leave the field.
'----------------------------------------------------------------------
Private Sub txtEffectiveDate_LostFocus()
    ' *********************************************************************
    ' ** Don't have the event handler try to do any parsing.  Just pass  **
    ' ** the .Text value to the validation function.  If a date comes    **
    ' ** back, reformat it to "look" like a date and move on.  Otherwise **
    ' ** pop up an "error" message and return focus to the TextBox for   **
    ' ** the user to correct their input.                                **
    ' *********************************************************************
    Dim TempDate As Date

    TempDate = CheckForValidDate(Me.txtEffectiveDate.Text)

    If TempDate > #12:00:00 AM# Then
        ' If a valid Date is returned, put the formatted String value
        ' into the TextBox and move on.
        Me.txtEffectiveDate.Text = Format(TempDate, "mm/dd/yy")
    Else
        ' If the Date value is not valid (#12:00:00 AM#), notify the
        ' user and refocus on the TextBox to force the user to
        ' correct the input before continuing.
        MsgBox "The date you entered was not valid." & vbCrLf & vbCrLf & _
               "Please enter two digits for the month, two digits for the day and" & vbCrLf & _
               "two digits for the year." & vbCrLf & vbCrLf & _
               "For example, today's date should be entered as either " & Format(Now, "mmddyy") & vbCrLf & _
               " or " & Format(Now, "mm/dd/yy") & ".", _
               vbOKOnly + vbExclamation, "INVALID INPUT FORMAT"
        Me.txtEffectiveDate.SetFocus
        Me.txtEffectiveDate.SelStart = 0
        Me.txtEffectiveDate.SelLength = Len(Me.txtEffectiveDate.Text)
    End If
End Sub

'----------------------------------------------------------------------
' Attempts to convert the String input to a Date value.  If the String
' value is already a Date (i.e., "1/1/16" or similar), go ahead and
' assume that the user wants that date and return it as a Date value.
' Otherwise, strip any non-numeric characters and break apart the input
' to pass along for further validation.
'----------------------------------------------------------------------
Private Function CheckForValidDate(ByVal DateStr As String) As Date
    Dim TempDate As Date

    If IsDate(DateStr) Then
        ' If the String value is already in a date format, 
        ' just return the Date value of the String.
        TempDate = CDate(DateStr)
    Else
        Dim TempStr As String
        Dim CurrentChar As String
        Dim TempYear As Integer
        Dim TempMonth As Integer
        Dim TempDay As Integer
        Dim I As Integer

        ' Strip all non-numeric characters to get a purely numeric string.
        For I = 1 To Len(DateStr)
            CurrentChar = Mid(DateStr, I, 1)

            If IsNumeric(CurrentChar) Then
                TempStr = TempStr & CurrentChar
            End If
        Next I

        ' The all-numeric string should be exactly six characters
        ' (for this application).
        If Len(Trim(TempStr)) = 6 Then
            Dim NewDateStr As String

            ' Break the numeric string into the component parts -
            ' Month, Day, and Year.  At six characters, there should
            ' be two characters for each element.
            TempMonth = CInt(Left(TempStr, 2))
            TempDay = CInt(Mid(TempStr, 3, 2))
            TempYear = CInt(Right(TempStr, 2))

            ' Now pass the individual values to the second part of
            ' the validation to ensure each of the individual values
            ' falls within acceptable ranges.
            NewDateStr = GetValidDateString(TempMonth, TempDay, TempYear)

            ' If the returned String value is not empty, then convert
            ' it to a Date value for returning to the calling method
            If Len(Trim(NewDateStr)) > 0 Then
                TempDate = CDate(NewDateStr)
            End If
        End If
    End If

    CheckForValidDate = TempDate
End Function

'----------------------------------------------------------------------
' Using numeric values for Month, Day, and Year, attempt to build a
' valid Date in mm/dd/yy format.
'----------------------------------------------------------------------
Private Function GetValidDateString(ByVal intMonth As Integer, ByVal intDay As Integer, ByVal intYear As Integer) As String
    Dim ReturnStr As String

    ReturnStr = ""

    If intMonth >= 1 And intMonth <= 12 Then
        Select Case intMonth
            Case 1, 3, 5, 7, 8, 10, 12
                ' January, March, May, July, August, October and December
                ' have 31 days.
                If intDay >= 1 And intDay <= 31 Then
                    ReturnStr = intMonth & "/" & intDay & "/" & intYear
                End If
            Case 4, 6, 9, 11
                ' April, June, September and November
                ' have 30 days
                If intDay >= 1 And intDay <= 30 Then
                    ReturnStr = intMonth & "/" & intDay & "/" & intYear
                End If
            Case 2
                ' Depending on whether it is a Leap Year (every four years),
                ' February may have 28 or 29 days.
                If intYear Mod 4 = 0 Then
                    If intDay >= 1 And intDay <= 29 Then
                        ReturnStr = intMonth & "/" & intDay & "/" & intYear
                    End If
                Else
                    If intDay >= 1 And intDay <= 28 Then
                        ReturnStr = intMonth & "/" & intDay & "/" & intYear
                    End If
                End If
        End Select
    End If

    ' Return the recombined string to the calling function.
    GetValidDateString = ReturnStr
End Function