将当地时间转换为utc

时间:2010-07-28 18:46:07

标签: vb.net

我有以下功能来获取时间。 dtuniversal我传递给sql server数据类型时间的stroed proc。它工作正常至东下午6点(即23 utc)它在东部时间晚上7点(24 utc)失败我收到错误“此元数据的值无效”。

Private Function GetUTCTime(ByVal time As TimeSpan) As TimeSpan

  Dim dt As New DateTime(time.Ticks)
  dt = dt.ToUniversalTime()
  Dim dtUniversal As New TimeSpan(dt.Ticks)
  Return dtUniversal

 End Function

1 个答案:

答案 0 :(得分:0)

以下测试代码表明应该查看变量time(aTimeSpan)。

Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button1.Click


    Dim ts As New TimeSpan(DateTime.Now.Ticks) 'create a test timespan
    'Dim ts As New TimeSpan(0,0,0) 'create a test timespan
    Dim oneHr As New TimeSpan(1, 0, 0) 'one hour increments

    For x As Integer = 0 To 24 '25 calls to GetUTCTime
        Debug.WriteLine("     '" & GetUTCTime(ts).ToString)
        ts = ts.Add(oneHr) 'add one hour
    Next
End Sub

Private Function GetUTCTime(ByVal aTimeSpan As TimeSpan) As TimeSpan
    'i don't like to use variable names that are keywords
    Dim dt As New DateTime(aTimeSpan.Ticks)
    dt = dt.ToUniversalTime()
    Dim dtUniversal As New TimeSpan(dt.Ticks)
    Return dtUniversal

End Function

'debug output
'733980.22:23:08.8112022
'733980.23:23:08.8112022
'733981.00:23:08.8112022
'733981.01:23:08.8112022
'733981.02:23:08.8112022
'733981.03:23:08.8112022
'733981.04:23:08.8112022
'733981.05:23:08.8112022
'733981.06:23:08.8112022
'733981.07:23:08.8112022
'733981.08:23:08.8112022
'733981.09:23:08.8112022
'733981.10:23:08.8112022
'733981.11:23:08.8112022
'733981.12:23:08.8112022
'733981.13:23:08.8112022
'733981.14:23:08.8112022
'733981.15:23:08.8112022
'733981.16:23:08.8112022
'733981.17:23:08.8112022
'733981.18:23:08.8112022
'733981.19:23:08.8112022
'733981.20:23:08.8112022
'733981.21:23:08.8112022
'733981.22:23:08.8112022

如果您只是从本地更改为UTC并返回:

'a test date in local time
Dim d As DateTime = DateTime.Now
'convert local to UTC
Dim u As DateTime = d.ToUniversalTime
'convert UTC to local
Dim nd As DateTime = u.ToLocalTime

你要么比这更难,要么我错过了什么

    Dim d As DateTime = DateTime.Parse("10:00:00") 'this is local central daylight
    Dim u As DateTime = d.ToUniversalTime 'this is universal
    d = u.ToLocalTime 'double check