Converting to and from VB6 Date to Unix / POSIX time

Visual Basic 6 as a language may slowly be falling into disuse and is a language which is no longer supported by Microsoft but we still need to interface old and new systems from time to time.
The rise of PHP, Ruby and other languages which have roots in the Unix environment converting date time values from Unix time to the IEEE 64 bit value used by VBScript is common task which can sometimes prove to be a bit of a headache. However, the conversion is actually quite simple.

Unix represents time by counting the seconds since the Unix epoch, which is January 1st 1970 00:00:00 UTC. Most systems today use a 32 bit signed integer to hold this value allowing it to represent dates and times between December 13th 1901 and January 19th 2038

Thus to convert Unix Time to a Date value useful to Visual Basic we need only add the number of seconds in the value to the date 1/1/1970 00:00:00 UTC. This can easily be done using the DateAdd function:

Function FromUnixTime(UnixTime As Long) As Date
FromUnixTime = DateAdd("s", UnixTime, DateSerial(1970, 1, 1))
End Function

Converting from Visual Basic to Unix Time is just as simple save that Technically Visual Basic can represent Dates and Times outside that which Unix Time can represent. To do the conversion we need only find the number of seconds from Unix epoch to our target date, for which we can use the DateDiff function:

Function ToUnixTime(time As Date) As Long
ToUnixTime = DateDiff("s", DateSerial(1970, 1, 1), time)
End Function

Note: Should the date value in Visual Basic be beyond a date which Unix Time can represent then ToUnixTime will throw and overflow error.

About tc

tc is a Hull based Computer Programmer with over 15 years experience in Software Development. He has developed countless Multi-Tear Desktop Applications and web applications for business in both the UK and abroad. Currently tc spends most of his time developing web sites / applications in PHP and desktop software in C#
This entry was posted in PHP, VB6. Bookmark the permalink.

Comments are closed.