在 VB6 中将芬兰日期字符串解析为日期类型

发布于 2024-12-04 10:19:57 字数 297 浏览 1 评论 0原文

我得到一个芬兰日期字符串,如下所示:

29.7.2011 9:27

我正在尝试将此字符串转换为 VB6 中的 Date 对象。我尝试过使用 Format 函数,但它似乎没有吞下日期字符串,或者我做错了什么。这些是我尝试过的一些方法:

theDate = Format(dateString, "General Date")

theDate = Format(dateString, "DD.MM.YYYY MM:HH")

有什么想法吗?谢谢。

I'm getting a Finnish date string that looks like:

29.7.2011 9:27

I'm trying to cast this string to a Date object in VB6. I've tried using the Format function but it doesn't seem to swallow the date string or I'm doing something wrong. These are some approaches I've tried:

theDate = Format(dateString, "General Date")

theDate = Format(dateString, "DD.MM.YYYY MM:HH")

Any ideas? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风吹雨成花 2024-12-11 10:19:57

您可以调用 OLE 自动化库(VB6 在内部使用它来处理许多事情,包括类型转换),而不是自己手动解析字符串,这很容易出错,而且如果您必须处理多种日期格式,这会变得混乱。为您进行转换。它可以将 Windows 支持的任何日期/时间格式的字符串转换回原始日期

全面披露:我同意 迪安娜的
回答
:一般来说,您应该尝试使用明确的日期/时间
在将日期与字符串相互转换时使用格式,但如果您不能这样做
由于某种原因,这里概述的解决方案应该相当强大,只要您提前知道传入日期字符串将采用什么特定格式。

下面是使用 DateFromString 函数的示例VarDateFromStr内部函数将格式化的日期/时间字符串转换为日期

用法示例

将芬兰语日期字符串转换为 日期 并显示它:

MsgBox DateFromString("29.7.2011 9:27", fl_FI)

在我的机器上(美国英语设置),这显示“7/29/2011 9:27 AM” ,这是正确的日期和时间(7 月 29 日)。

代码

将下面的代码放入项目中的新模块(.bas 文件)中以使用它。该代码当前支持解析美国英语 (en_US) 和芬兰语 (fl_FI) 日期字符串,但您可以根据需要添加对更多区域设置的支持。请参阅Microsoft 分配的区域设置 ID 了解完整信息区域设置 ID 列表。


Option Explicit

Public Enum LocaleIDs
    en_US = &H409       ' English (United States)
    fl_FI = &H40B       ' Finnish
    ' [[ Add other Locale ID's here as needed ]] '
End Enum

Private Declare Function VarDateFromStr Lib "oleaut32.dll" ( _
    ByVal psDateIn As Long, _
    ByVal lcid As Long, _
    ByVal uwFlags As Long, _
    ByRef dtOut As Date) As Long

Private Const S_OK = 0
Private Const DISP_E_BADVARTYPE = &H80020008
Private Const DISP_E_OVERFLOW = &H8002000A
Private Const DISP_E_TYPEMISMATCH = &H80020005
Private Const E_INVALIDARG = &H80070057
Private Const E_OUTOFMEMORY = &H8007000E

'
' Converts a date string in the specified locale to a VB6 Date.
'
' Example:
'
'   Convert a Finnish date string as follows:
'
'   DateFromString("29.7.2011 9:27", fl_FI)
'
Public Function DateFromString(ByVal sDateIn As String, ByVal lcid As LocaleIDs) As Date

    Dim hResult As Long
    Dim dtOut As Date

    ' Do not want user's own settings to override the standard formatting settings
    ' if they are using the same locale that we are converting from.
    '
    Const LOCALE_NOUSEROVERRIDE = &H80000000

    ' Do the conversion
    hResult = VarDateFromStr(StrPtr(sDateIn), lcid, LOCALE_NOUSEROVERRIDE, dtOut)

    ' Check return value to catch any errors.
    '
    ' Can change the code below to return standard VB6 error codes instead
    ' (i.e. DISP_E_TYPEMISMATCH = "Type Mismatch" = error code 13)
    '
    Select Case hResult

        Case S_OK:
            DateFromString = dtOut
        Case DISP_E_BADVARTYPE:
            Err.Raise 5, , "DateFromString: DISP_E_BADVARTYPE"
        Case DISP_E_OVERFLOW:
            Err.Raise 5, , "DateFromString: DISP_E_OVERFLOW"
        Case DISP_E_TYPEMISMATCH:
            Err.Raise 5, , "DateFromString: DISP_E_TYPEMISMATCH"
        Case E_INVALIDARG:
            Err.Raise 5, , "DateFromString: E_INVALIDARG"
        Case E_OUTOFMEMORY:
            Err.Raise 5, , "DateFromString: E_OUTOFMEMORY"
        Case Else
            Err.Raise 5, , "DateFromString: Unknown error code returned from VarDateFromStr (0x" & Hex(hResult) & ")"
    End Select

End Function

Rather than manually parsing the string yourself, which is prone to errors, and which gets messy if you have to deal with multiple date formats, you can call out to the OLE Automation library (which VB6 uses internally for many things, including type conversions) to do the conversion for you. It can convert strings in any date/time format supported by Windows back into a raw Date.

Full disclosure: I agree with the sentiment in Deanna's
answer
: in general, you should try to use an unambiguous date/time
format when converting dates to and from strings, but if you cannot do
this for some reason, the solution outlined here should be fairly robust, as long as you know ahead of time what specific format the incoming date string will be in.

Below is an example of a DateFromString function that uses the VarDateFromStr function internally to convert a formatted date/time String into a Date.

Example Usage

Convert a Finnish date string to a Date and display it:

MsgBox DateFromString("29.7.2011 9:27", fl_FI)

On my machine (US English settings), this displays "7/29/2011 9:27 AM", which is the correct date and time (July 29).

Code

Place the code below into a new module (.bas file) in your project to use it. The code currently supports parsing US English (en_US) and Finnish (fl_FI) date strings, but you can add support for more locales if needed. See Locale IDs assigned by Microsoft for a complete list of locale ID's.


Option Explicit

Public Enum LocaleIDs
    en_US = &H409       ' English (United States)
    fl_FI = &H40B       ' Finnish
    ' [[ Add other Locale ID's here as needed ]] '
End Enum

Private Declare Function VarDateFromStr Lib "oleaut32.dll" ( _
    ByVal psDateIn As Long, _
    ByVal lcid As Long, _
    ByVal uwFlags As Long, _
    ByRef dtOut As Date) As Long

Private Const S_OK = 0
Private Const DISP_E_BADVARTYPE = &H80020008
Private Const DISP_E_OVERFLOW = &H8002000A
Private Const DISP_E_TYPEMISMATCH = &H80020005
Private Const E_INVALIDARG = &H80070057
Private Const E_OUTOFMEMORY = &H8007000E

'
' Converts a date string in the specified locale to a VB6 Date.
'
' Example:
'
'   Convert a Finnish date string as follows:
'
'   DateFromString("29.7.2011 9:27", fl_FI)
'
Public Function DateFromString(ByVal sDateIn As String, ByVal lcid As LocaleIDs) As Date

    Dim hResult As Long
    Dim dtOut As Date

    ' Do not want user's own settings to override the standard formatting settings
    ' if they are using the same locale that we are converting from.
    '
    Const LOCALE_NOUSEROVERRIDE = &H80000000

    ' Do the conversion
    hResult = VarDateFromStr(StrPtr(sDateIn), lcid, LOCALE_NOUSEROVERRIDE, dtOut)

    ' Check return value to catch any errors.
    '
    ' Can change the code below to return standard VB6 error codes instead
    ' (i.e. DISP_E_TYPEMISMATCH = "Type Mismatch" = error code 13)
    '
    Select Case hResult

        Case S_OK:
            DateFromString = dtOut
        Case DISP_E_BADVARTYPE:
            Err.Raise 5, , "DateFromString: DISP_E_BADVARTYPE"
        Case DISP_E_OVERFLOW:
            Err.Raise 5, , "DateFromString: DISP_E_OVERFLOW"
        Case DISP_E_TYPEMISMATCH:
            Err.Raise 5, , "DateFromString: DISP_E_TYPEMISMATCH"
        Case E_INVALIDARG:
            Err.Raise 5, , "DateFromString: E_INVALIDARG"
        Case E_OUTOFMEMORY:
            Err.Raise 5, , "DateFromString: E_OUTOFMEMORY"
        Case Else
            Err.Raise 5, , "DateFromString: Unknown error code returned from VarDateFromStr (0x" & Hex(hResult) & ")"
    End Select

End Function

人生戏 2024-12-11 10:19:57

您可以按以下方式使用 DateSerial 和 'TimeSerial'

dateString = "29.7.2011 9:27"

Dim theDate as Date

dim yyyy as Integer
dim mm as Integer
dim dd as Integer
dim hh as integer
dim mm as integer

yyyy = mid(dateString,6,4)
mm = mid(dateString,4,1)
dd = mid(dateString,1,2)
hh = mid(dateString,11,1)
mm = mid(dateString,13,2)

theDate = DateSerial(yyyy,mm,dd) + TimeSerial(hh,mm,0)

现在您 theDate 是一个 Date 对象,并且可以按照您想要的方式格式化

MsgBox Format(theDate,"yyyy-MMM-dd")  'This will display the a message with 2011-Jul-29

如果您的日期字符串没有用零填充(例如:2.4.2011 而不是 02.04.2011)那么您将需要循环遍历字符串以查找您需要的日期的位和部分。

You can use DateSerial and 'TimeSerial' in the following way

dateString = "29.7.2011 9:27"

Dim theDate as Date

dim yyyy as Integer
dim mm as Integer
dim dd as Integer
dim hh as integer
dim mm as integer

yyyy = mid(dateString,6,4)
mm = mid(dateString,4,1)
dd = mid(dateString,1,2)
hh = mid(dateString,11,1)
mm = mid(dateString,13,2)

theDate = DateSerial(yyyy,mm,dd) + TimeSerial(hh,mm,0)

now you theDate is a Date object and can be formatted the way you want

MsgBox Format(theDate,"yyyy-MMM-dd")  'This will display the a message with 2011-Jul-29

If your date string is not padded with zeros (for example: 2.4.2011 instead of 02.04.2011) then you will need to loop through the string to find the bits and parts of the date that you will be needing.

霊感 2024-12-11 10:19:57

芬兰系统应该能够使用 CDate() 正确解析这些内容。如果您在非芬兰系统上解析它并且格式是固定的,那么您将需要将其拆分为代码:

Dim Parts() as string, dateParts() As String, timeParts() as string
parts = Split(dateString, " ")
dateParts = Split(parts(0), ".") 
timeParts = Split(parts(1), ":")
theDate = DateSerial(dateParts(2), dateParts(1), dateParts(0)) + TimeSerial(timeParts(0), timeParts(1), 0)

您可能想要添加错误处理和健全性检查,但这是基本思想。

请注意,除非使用非常明确的明确商定的格式,否则在日期与字符串值之间进行转换很容易出错例如ISO 8601RFC 822 日期和 iCal RFC 2445 标准。

Finnish systems should be able to parse these correctly using CDate(). If you're parsing it on a non finnish system and the format is fixed, then you will need to split it up in code:

Dim Parts() as string, dateParts() As String, timeParts() as string
parts = Split(dateString, " ")
dateParts = Split(parts(0), ".") 
timeParts = Split(parts(1), ":")
theDate = DateSerial(dateParts(2), dateParts(1), dateParts(0)) + TimeSerial(timeParts(0), timeParts(1), 0)

You will probbaly want to add error handling and sanity checking to that but that is the basic idea.

Note that converting dates to and from string values will be error prone unless using very explicit unambigious agreed formats like ISO 8601, RFC 822 dates, and the iCal RFC 2445 standard.

昇り龍 2024-12-11 10:19:57

解析充其量是混乱的,但这里有一个更短的示例如何做到这一点

Private Sub Command1_Click()
    MsgBox Format$(TryParse("29.7.2011 9:27"), "yyyymmdd hh:mm:ss")
End Sub

Private Function TryParse(sFinnishDate As String) As Date
    Dim vSplit As Variant

    vSplit = Split(Replace(Replace(sFinnishDate, ".", " "), ":", " "))
    On Error Resume Next
    TryParse = DateSerial(vSplit(2), vSplit(1), vSplit(0)) + TimeSerial(vSplit(3), vSplit(4), 0)
    On Error GoTo 0
End Function

Parsing is messy at best but here is a shorter sample how to do it

Private Sub Command1_Click()
    MsgBox Format$(TryParse("29.7.2011 9:27"), "yyyymmdd hh:mm:ss")
End Sub

Private Function TryParse(sFinnishDate As String) As Date
    Dim vSplit As Variant

    vSplit = Split(Replace(Replace(sFinnishDate, ".", " "), ":", " "))
    On Error Resume Next
    TryParse = DateSerial(vSplit(2), vSplit(1), vSplit(0)) + TimeSerial(vSplit(3), vSplit(4), 0)
    On Error GoTo 0
End Function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文