我正在尝试做一个小助手应用程序,以帮助阅读SCCM日志。在分析时区偏移之前,解析日期是非常简单的。它通常以“+??”的形式出现。字面例子:"11-01-2016 11:44:25.630+480“
大多数情况下,DateTime.parse()都能很好地处理这个问题。但偶尔我会遇到一个时间戳,它会抛出一个异常。我搞不懂为什么。这是我需要帮助的地方。参见下面的示例代码:
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = "11-07-2016 16:43:51.541+600"
Dim dateStr_B As String = "11-01-2016 11:44:25.630+480"
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)如果运行,dateStr_B似乎是一个无效的时间戳?为什么会这样呢?我试图弄清楚如何使用.ParseExact()格式使用“zzz”来处理+480,如下所示,数据格式化MSDN
我是不是漏了带时区偏移的东西?我到处搜索SCCM日志,但是这些SCCM日志似乎使用了一种表示偏移量的非标准方法。任何见解都将不胜感激。
发布于 2016-11-15 16:03:59
问题是+480确实是一个无效的偏移量。来自UTC的偏移量的格式(使用"zzz“自定义格式说明程序时产生的格式是小时和分钟)。+600比世界协调时提前6小时零分钟,这是有效的。+480将比世界协调时提前4小时80分钟,这是无效的,因为分钟数不能超过59分钟。
如果您有一些外部的日期和时间字符串,它使用的偏移量仅为几分钟(即+600表示10小时,+480表示8小时),则需要在使用DateTime.Parse或DateTime.ParseExact之前调整偏移量。
编辑以下函数以分钟为单位,获得一个带有正数或负偏移量(任意数字)的时间戳,并返回一个DateTime。如果时间戳不是有效格式,则抛出ArgumentException。
Public Function DateTimeFromSCCM(ByVal ts As String) As DateTime
Dim pos As Integer = ts.LastIndexOfAny({"+"c, "-"c})
If pos < 0 Then Throw New ArgumentException("Timestamp must contain a timezone offset", "ts")
Dim offset As Integer
If Not Integer.TryParse(ts.Substring(pos + 1), offset) Then
Throw New ArgumentException("Timezone offset is not numeric", "ts")
End If
Dim hours As Integer = offset \ 60
Dim minutes As Integer = offset Mod 60
Dim timestamp As String = ts.Substring(0, pos + 1) & hours.ToString & minutes.ToString("00")
Dim result As DateTime
If Not DateTime.TryParse(timestamp, result) Then
Throw New ArgumentException("Invalid timestamp", "ts")
End If
Return result
End Function发布于 2016-11-15 17:49:22
谢谢你的洞察力。我有种感觉,我需要手动处理。我只是想确保在这个过程中我不会错过一些简单的东西。我对日期和时间格式的了解有点不足。
因此,我修改了我的代码,以便它处理偏移量。当然,我必须在最终产品中添加更多的输入验证。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = correctOffset("11-07-2016 16:43:51.541+600")
Dim dateStr_B As String = correctOffset("11-07-2016 16:43:51.541+480")
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
End Sub
Public Function correctOffset(ByVal ts As String)
Dim offset As Integer = CInt(ts.Substring(ts.Length - 3))
Dim offHour As Integer = offset / 60
Dim offMin As Integer = offset - (offHour * 60)
Dim strhour As String = Nothing
Dim strmin As String = Nothing
If offHour <= 9 Then
strhour = "0" & CStr(offHour)
Else
strhour = CStr(offHour)
End If
If offMin <= 9 Then
strmin = "0" & CStr(offMin)
Else
strmin = CStr(offMin)
End If
Return ts.Substring(0, ts.Length - 3) & strhour & ":" & strmin
End Functionhttps://stackoverflow.com/questions/40613736
复制相似问题