Converting DateTime to number of seconds in VB .NET
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
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.