Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DateTime to number of seconds in VB .NET

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?

like image 492
GVillani82 Avatar asked Oct 28 '12 11:10

GVillani82


2 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
like image 155
Oded Avatar answered Oct 15 '22 13:10

Oded


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.

like image 22
Hans Passant Avatar answered Oct 15 '22 13:10

Hans Passant