将文本中的UTC时间戳转换为Excel日期

时间:2019-06-14 17:47:42

标签: excel vba date time

我在Excel工作簿中有

格式的日期

2019年2月7日星期四09:38:41 UTC + 10

它们的格式为常规/文本。需要转换为实际的Excel日期/时间进行排序。

尝试解析和拆分,但并不总是有效并且非常笨拙

3 个答案:

答案 0 :(得分:3)

解析似乎是唯一明智的方法。看起来像是正则表达式的工作。

此函数需要引用VBScript_RegEp_55类型库:

Public Function ParseUtcDate(ByVal value As String, Optional ByVal utcOffset As Double = 0) As Date
    Const pattern As String = "(\w+) (\w+) (\d+) (\d\d:\d\d:\d\d) UTC((\+|\-)\d+) (\d\d\d\d)"
    With New RegExp
        .IgnoreCase = True
        .Global = True
        .pattern = pattern

        Dim mc As MatchCollection
        Set mc = .Execute(value)
    End With

    Dim m As Match
    Set m = mc(0)

    Dim monthNamePart As String
    monthNamePart = m.SubMatches(1)

    Dim dayOfMonthPart As String
    dayOfMonthPart = m.SubMatches(2)

    Dim timePart As String
    timePart = m.SubMatches(3)

    Dim utcOffsetPart As String
    utcOffsetPart = m.SubMatches(4)

    Dim yearPart As String
    yearPart = m.SubMatches(6)

    Dim dateParts As Variant
    dateParts = VBA.Array(monthNamePart, dayOfMonthPart, yearPart, timePart)

    Dim formattedDate As String
    formattedDate = VBA.Join(dateParts, " ")

    Dim offset As Double
    offset = CDbl(utcOffsetPart)

    Dim offsetHours As Double
    offsetHours = offset / 24

    Dim targetOffset As Double
    targetOffset = utcOffset / 24

    ParseUtcDate = CDate(formattedDate) - offsetHours + targetOffset

End Function

用法:

?ParseUtcDate("Thu Feb 7 09:38:41 UTC+10 2019", 10)
 2/7/2019 9:38:41 AM

?ParseUtcDate("Thu Feb 7 09:38:41 UTC+10 2019")
 2/6/2019 11:38:41 PM

?ParseUtcDate("Thu Feb 7 09:38:41 UTC+10 2019", -5)
 2/6/2019 6:38:41 PM

答案 1 :(得分:1)

出于兴趣,如果您具有带有TEXTJOIN函数的Excel 2016+,则可以使用FILTERXML来解析句段,然后创建日期/时间字符串,Excel会将其解释为真实的日期:

本地时间

=TEXTJOIN(" ",TRUE,INDEX(FILTERXML("<t><s>" & SUBSTITUTE(A2," ","</s><s>")& "</s></t>","//s"),N(IF(1,{3,2,6}))))
+FILTERXML("<t><s>" & SUBSTITUTE(A2," ","</s><s>")& "</s></t>","//s[4]")

UTC时间

=TEXTJOIN(" ",TRUE,INDEX(FILTERXML("<t><s>" & SUBSTITUTE(A2," ","</s><s>")& "</s></t>","//s"),N(IF(1,{3,2,6}))))
+FILTERXML("<t><s>" & SUBSTITUTE(A2," ","</s><s>")& "</s></t>","//s[4]")
-SUBSTITUTE(FILTERXML("<t><s>" & SUBSTITUTE(A2," ","</s><s>")& "</s></t>","//s[5]"),"UTC","")/24

enter image description here

答案 2 :(得分:0)

我没有任何“笨拙”的VBA代码,但我已经制定了工作表公式。

'for localized date/time
=SUM(DATEVALUE(TRIM(MID(REPLACE(A2, FIND(" ", A2, 9), 16, ", "), 4, LEN(A2)))),
     TIMEVALUE(MID(A2, FIND(" ", A2, 9)+1, 8)))
'for UTC date time
=SUM(DATEVALUE(TRIM(MID(REPLACE(A2, FIND(" ", A2, 9), 16, ", "), 4, LEN(A2)))),
     TIMEVALUE(MID(A2, FIND(" ", A2, 9)+1, 8)),
     -PRODUCT(VALUE(MID(A2, FIND("UTC", A2)+3, 3)), TIME(1, 0, 0)))

usage example in Excel worksheet