Converting DateTime to number of seconds in VB .NET

GVillani82 picture GVillani82 · Oct 28, 2012 · Viewed 24k times · Source

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?

Answer

Oded picture Oded · Oct 28, 2012

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