我们有一个VB6应用程序(在COM组件中),它使用CDate()获取字符串并将其强制转换为Date,以存储在数据库中.
例如,根据我们是否希望应用程序以dd / MM / yy或MM / dd / yy进行通话,我们必须更改COM应用程序的标识用户的区域设置. (现在我们唯一的选择是a nasty hack.)
我们有一个日期格式字符串,用于格式化所有输出日期,并假定日期
如果这是.NET,我们将使用DateTime.ParseExact并且不要笑.为此唯一目的调用以.NET编写的COM对象是一种选择.是否有一个不同的或更好的选项,涉及Format命令周围的一些黑魔法,或一个长的可重用函数,根据格式字符串等标记日期?
这应该很接近,虽然它将分隔符硬编码为“/”并且窗口YY年份为50:
原文链接:https://www.f2er.com/vb/255607.htmlPrivate Function ParseDate(ByVal DateString As String,_ ByVal DatePattern As String) As Date 'DateString: i/j/k formatting. 'DatePattern: i/j/k formatting,each to be: ' M or MM for month position. ' D or DD for day position. ' YY or YYYY for year position,if YY ' then century windowed at 50. Dim strStringParts() As String Dim strPatternParts() As String Dim intPart As Integer,intscore As Integer Dim intMonth As Integer,intDay As Integer,intYear As Integer Const DELIM As String = "/" Const YYWINDOW As Integer = 50 strStringParts = Split(DateString,DELIM) strPatternParts = Split(UCase$(DatePattern),DELIM) For intPart = 0 To UBound(strStringParts) If intPart > UBound(strPatternParts) Then Err.Raise 5,"ParseDate" End If Select Case strPatternParts(intPart) Case "M","MM" intMonth = CInt(strStringParts(intPart)) intscore = intscore Or &H1 Case "D","DD" intDay = CInt(strStringParts(intPart)) intscore = intscore Or &H2 Case "YY" intYear = CInt(strStringParts(intPart)) If 0 > intYear Or intYear > 99 Then Err.Raise 5,"ParseDate" End If intYear = intYear + IIf(intYear < YYWINDOW,2000,1900) intscore = intscore Or &H4 Case "YYYY" intYear = CInt(strStringParts(intPart)) If 100 > intYear Or intYear > 9999 Then Err.Raise 5,"ParseDate" End If intscore = intscore Or &H4 Case Else Err.Raise 5,"ParseDate" End Select Next If intscore = &H7 Then ParseDate = DateSerial(intYear,intMonth,intDay) Else Err.Raise 5,"ParseDate" End If End Function