Convert DateTime to seconds in VB.NET

To convert the number of seconds in DateTime to VB.NET, I use the following code:

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

where DataInSeconds is an integer containing the number of seconds (starting from 1/1/1970)

It works well. But I do not know how to do the inverse transform. (from DateTime to seconds). Can anybody help me?

+7
source share
4 answers

When you subtract DateTime instances from each other, you get a TimeSpan - you can use this to get the number of seconds:

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

1/1/1970 - Unix era. Remember that this is a UTC date; you cannot ignore this in conversions. Thus:

 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 

Beware of ToUnix (), DateTimeKind may be unspecified, as it was in your snippet. Instead, use DateTimeOffset to make it unique. And be sure to do something reasonable in 2038, when all this collapses.

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

Create a text box and a button and a label, put this code in the button and depending on whether you use microseconds (hold / 1000) or seconds (delete / 1000), you will see the date / time, etc.

0
source
 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 
0
source

All Articles