【问题标题】:Converting DateTime to number of seconds in VB .NET在 VB .NET 中将 DateTime 转换为秒数
【发布时间】:2012-10-28 11:51:50
【问题描述】:

为了将秒数转换为日期时间,在 VB .NET 中,我使用以下代码:

    Dim startDate As New DateTime(1970, 1, 1)
    Dim targetDate As DateTime
    Dim noOfSeconds As Integer = DataInSeconds

    targetDate = startDate.AddSeconds(noOfSeconds)

其中 DataInSeconds 是一个包含秒数的整数(从 1970 年 1 月 1 日开始)

这很好用。但我不知道如何进行逆变换。 (从 DateTime 到秒数)。谁能帮帮我?

【问题讨论】:

    标签: vb.net datetime time datetime-conversion


    【解决方案1】:

    当您将 DateTime 实例彼此相减时,您会得到 TimeSpan - 您可以使用它来获取秒数:

    Dim startDate As New DateTime(1970, 1, 1)
    Dim noOfSeconds As Integer
    
    noOfSeconds = (currentDate - startDate).TotalSeconds
    

    【讨论】:

      【解决方案2】:

      1/1/1970 是 Unix 时代。请注意,它是 UTC 日期,您不能在转换中忽略它。因此:

      Module DateConversion
          Public ReadOnly Property Epoch() As DateTime
              Get
                  Return New DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
              End Get
          End Property
      
          Public Function FromUnix(ByVal seconds As Integer, local As Boolean) As DateTime
              Dim dt = Epoch.AddSeconds(seconds)
              If local Then dt = dt.ToLocalTime
              Return dt
          End Function
      
          Public Function ToUnix(ByVal dt As DateTime) As Integer
              If dt.Kind = DateTimeKind.Local Then dt = dt.ToUniversalTime
              Return CInt((dt - Epoch).TotalSeconds)
          End Function
      End Module
      

      注意 ToUnix(),DateTimeKind 可能未指定,就像在您的 sn-p 中一样。考虑改用 DateTimeOffset 以使其明确。当这一切都崩溃时,一定要在 2038 年做一些合理的事情。

      【讨论】:

        【解决方案3】:
        Label1.Text = New DateTime(1970, 1, 1, 0, 0, 0, 
            DateTimeKind.Utc).AddSeconds(CLng(TextBox1.Text) / 1000)      
        

        制作一个文本框、一个按钮和一个标签,将此代码放入按钮中,根据您使用的是微秒(保留 /1000)还是秒(删除 /1000)将显示日期/时间等。

        【讨论】:

          【解决方案4】:
          Public Function Date2Unix(ByVal vDate As Date) As Long
           Return (vDate - #1970/01/01#).TotalSeconds
          End Function
          
          Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
           MsgBox(Date2Unix(Now()))
          End Sub
          

          【讨论】:

          • 嗨!请为解决方案添加解释,因为 SO 通常不鼓励仅使用代码的答案。谢谢! -- 来自评论。
          猜你喜欢
          • 1970-01-01
          • 2022-01-17
          • 1970-01-01
          • 2012-08-20
          • 2011-11-08
          • 2020-03-04
          • 2012-09-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多