tmighty
tmighty

Reputation: 11409

Converting unix time to DateTime

I would like to convert a Unix time stamp to a VB.NET DateTime.

I have tried

Public Function UnixToDateTime(ByVal strUnixTime As String) As DateTime

    Dim nTimestamp As Double = strUnixTime
    Dim nDateTime As System.DateTime = New System.DateTime(1970, 1, 1, 0, 0, 0, 0)
    nDateTime.AddSeconds(nTimestamp)

    Return nDateTime

End Function

But when I feed it

strUnixTime = "1401093810"

I get the return value

nDateTime = #1/1/1970#

What am I doing wrong? Thank you

Upvotes: 3

Views: 17338

Answers (1)

Heinzi
Heinzi

Reputation: 172408

This line of code

nDateTime.AddSeconds(nTimestamp)

does not modify nDateTime. It's like writing a + 3 on a line by it's own -- a won't be modified.

It does, however, return a new DateTime object that contains the incremented value. So, what you actually wanted to write is:

nDateTime = nDateTime.AddSeconds(nTimestamp)

PS: It appears that your code does not use Option Strict On. It is strongly recommended that you activate Option Strict and use explicit instead of implicit conversions.

Upvotes: 10

Related Questions