Question

For converting number of seconds to DateTime, in 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)

This works good. But I don't know how make the inverse conversion. (from DateTime to number of seconds). Anyone can help me?

Was it helpful?

Solution

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

OTHER TIPS

1/1/1970 is the Unix epoch. Beware that it is a UTC date, you cannot ignore that 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

Watch out for ToUnix(), the DateTimeKind may be unspecified, as it was in your snippet. Consider using DateTimeOffset instead to make it unambiguous. And be sure to do something reasonable in 2038 when all of this comes tumbling down.

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

Make a textbox and a button and a label, put this code into the button and depending if you're using microseconds (keep the /1000) or seconds (delete the /1000) will show you the date/time etc.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top