2

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

  1. “2012 年 4 月 8 日 21:26:49”

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

任何人都可以帮忙吗?

4

3 回答 3

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 )(.*?)(?=\;)
于 2012-05-01T00:09:10.657 回答
1

正如罗密欧在他的回答中已经提到的那样,您需要使用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
于 2012-05-01T10:52:26.153 回答
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()例如重建它们。

于 2012-05-01T12:16:59.933 回答