Visual Basic Code Snippet - Convert Unix timestamp

Visual Basic Code Snippet - Convert Unix timestamp

Visual Basic Code Snippet - Convert Unix timestamp

(VB) Visual Basic code snippets convert date/time between DateTime and Unix timestamp. Most .Net base applications never use Unix timestamp, but if you want to create a application to interact with other application or sites, maybe built in PHP or Java, use these methods to convert Unix timestamp.

Bookmark:

Visual Basic Code Snippet - Convert Unix timestamp

These Visual Basic code snippets convert given Unix timestamp to DateTime and given DateTime to Unix timestamp. Unix timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

This method converts a Unix timestamp to its DateTime equivalent. Method returns converted result as DateTime data type.

''' <summary>
''' Methods to convert Unix time stamp to DateTime
''' </summary>
''' <param name="_UnixTimeStamp">Unix time stamp to convert</param>
''' <returns>Return DateTime</returns>
Public Function UnixTimestampToDateTime(ByVal _UnixTimeStamp As Long) As DateTime
    Return (New DateTime(1970, 1, 1, 0, 0, 0)).AddSeconds(_UnixTimeStamp)
End Function


This method converts a DateTime to its Unix timestamp equivalent. Method returns converted result as long data type.

''' <summary>
''' Methods to convert DateTime to Unix time stamp
''' </summary>
''' <param name="_UnixTimeStamp">Unix time stamp to convert</param>
''' <returns>Return Unix time stamp as long type</returns>
Public Function DateTimeToUnixTimestamp(ByVal _DateTime As DateTime) As Long
    Dim _UnixTimeSpan As TimeSpan = (_DateTime.Subtract(New DateTime(1970, 1, 1, 0, 0, 0)))
    Return CLng(Fix(_UnixTimeSpan.TotalSeconds))
End Function


Here are few simple examples showing how to use above methods (UnixTimestampToDateTime, DateTimeToUnixTimestamp) to convert date/time between DateTime and Unix timestamp.

' Convert current DateTime in Unix time stamp
Console.WriteLine("Current unix time stamp is : " & DateTimeToUnixTimestamp(DateTime.Now).ToString())

' convert Oct-07-1975 11:27 AM (15 Sec 37 MiliSec.) to Unix Time Stamp
Console.WriteLine("Oct-07-1975 11:27 AM (15 Sec 37 MiliSec.) to unix time stamp : " & DateTimeToUnixTimestamp(New DateTime(1975, 10, 7, 11, 27, 15, 37)).ToString())

' convert given Unix time stamp to DateTime and update dateTimePicker value
dateTimePicker1.Value = UnixTimestampToDateTime(181913235)


VB Keywords Used:

  • TimeSpan
  • DateTime
  • UtcNow
  • TotalSeconds

Code Snippet Information:

  • Applies To: Visual Studio, .Net, Visual Basic, VB, Date/Time, Timestamp, Unix Time, Unix Timestamp, Convert Unix Timestamp
  • Programming Language : Visual Basic (VB)

External Resources:

Leave a comment