从MS Access中的字符串中提取/转换日期

时间:2012-04-30 23:55:56

标签: regex ms-access vba

我正在尝试从具有以下模式的字符串中提取日期/时间,并将它们转换为Access中的日期类型。

  1. “08-Apr-2012 21:26:49”

  2. “...... SMITH,MD,JOHN(123)于2012年4月2日上午11:11:01确认;”

  3. 有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

试试这个

    Dim d As Date
    d = CDate("08-Apr-2012 21:26:49")
    Debug.Print Format(d, "dd-MMM-yyyy")
    Debug.Print Format(d, "h:m:s")

会给出

08-Apr-2012
21:26:49

使用此正则表达式获取“on”(即空格上的空格)和“;”之间的日期时间(之后的第一个分号)。

(?<=\ on )(.*?)(?=\;)

答案 1 :(得分:1)

正如罗密欧在his answer中已经提到的,您需要使用CDate()将带有效日期值的字符串转换为Date变量。

您可以从字符串中获取日期值,如下所示:
(假设字符串总是看起来像示例中的那个,“on”(带空格)在日期之前和“;”之后):

Public Function Test()

    Dim Source As String
    Dim Tmp As String
    Dim DateStart As Integer
    Dim DateEnd As Integer
    Dim DateValue As Date

    Source = "...Confirmed by SMITH, MD, JOHN (123) on 4/2/2012 11:11:01 AM;"

    'find the place in the source string where " on " ends
    DateStart = InStr(1, Source, " on ") + 4

    'find first semicolon after the date)
    DateEnd = InStr(DateStart, Source, ";")

    'get the part with the date
    Tmp = Mid(Source, DateStart, DateEnd - DateStart)

    'convert to date
    DateValue = CDate(Tmp)

End Function

答案 2 :(得分:0)

将此功能添加到VBA模块:

' ----------------------------------------------------------------------'
' Return a Date object or Null if no date could be extracted            '
' ----------------------------------------------------------------------'
Public Function ExtractDate(value As Variant) As Variant
    If IsNull(value) Then
        ExtractDate = Null
        Exit Function
    End If

    ' Using a static, we avoid re-creating the same regex object for every call '
    Static regex As Object
    ' Initialise the Regex object '
    If regex Is Nothing Then
        Set regex = CreateObject("vbscript.regexp")
        With regex
            .Global = True
            .IgnoreCase = True
            .MultiLine = True
            .pattern = "(\d+\/\d+/\d+\s+\d+:\d+:\d+\s+\w+|\d+-\w+-\d+\s+\d+:\d+:\d+)"
        End With
    End If
    ' Test the value against the pattern '
    Dim matches As Object
    Set matches = regex.Execute(value)
    If matches.count > 0 Then
        ' Convert the match to a Date if we can '
        ExtractDate = CDate(matches(0).value)
    Else
        ' No match found, jsut return Null '
        ExtractDate = Null
    End If
End Function

然后像这样使用它,例如在查询中:

SELECT ID, LogData, ExtractDate(LogData) as LogDate
FROM   MyLog

确保检查返回的日期格式是否正确并且对您有意义。 CDate()根据您的语言环境以不同方式解释日期字符串。

如果您没有获得所需的结果,则需要修改代码以分隔日期的各个组成部分,并使用DateSerial()重建它们。