2012-10-28 13 views
7

號用於轉換的秒數爲日期時間,在VB .NET,我使用以下代碼:轉換到日期時間的秒在VB .NET

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

    targetDate = startDate.AddSeconds(noOfSeconds) 

其中DataInSeconds是包含的秒數一個Integer(從1970年1月1日開始)

這很好。但我不知道如何進行逆轉換。 (從DateTime到秒數)。任何人都可以幫助我?

回答

8

當你減去彼此DateTime情況下,你會得到一個TimeSpan - 你可以用它來獲取的秒數:

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

noOfSeconds = (currentDate - startDate).TotalSeconds 
4

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可能未指定,因爲它在您的片段。考慮使用DateTimeOffset來代替它,使其明確無誤。 2038年,當所有這一切都崩潰時,一定要做一些合理的事情。

0
Label1.Text = New DateTime(1970, 1, 1, 0, 0, 0, 
    DateTimeKind.Utc).AddSeconds(CLng(TextBox1.Text)/1000)  

做一個文本框和按鈕和標籤,把這個代碼放到按鈕並根據若你使用微秒(保持/ 1000)或秒(刪除/ 1000),將顯示的日期/時間等

相關問題