Convert a Unix timestamp to a Visual FoxPro datetime
Converting between Unix and VFP datetime formats is surprisingly easy.
By Dan Macleod
In my current VFP development project, I have to work with data that originates in a Unix system, where datetimes are stored as Unix timestamps. Obviously, I prefer to use Visual FoxPro's native functions to process dates and datetimes, so I needed a way to convert between the Unix and VFP formats. This turned out to be extremely easy.
What exactly is a Unix timestamp?
Put simply, a Unix timestamp (sometimes called a Posix timestamp) represents the number of seconds that have elapsed since the start of the Unix "epoch", that is, since 00:00:00 on 1st January, 1970.
In fact, it's a little more complicated than that, for two reasons. First, it ignores leap seconds. So there will always be a very small disparity between Unix time and "true" time. Secondly, Unix time is based on Coordinated Universal Time (UTC), which means that it might need adjusting for a particular time zone. In practice, these issues rarely affect typical computer applications; they certainly didn't affect mine, and I decided to ignore them.
How to convert it
To convert a Unix timestamp to a FoxPro datetime, all you have to do is to add the number of seconds in the timestamp to the base date, like so:
* lnTimestamp contains the Unix timestamp ltFoxTime = DATETIME(1970, 1, 1, 0, 0, 0) + lnTimeStamp
Once you've done that, you can use VFP's full repertoire of functions to manipulate or display the datetime. Some examples:
* Convert from a datetime to a date ldFoxDate = TTOD(ltFoxTime) * Display the datetime in Windows short date format ? TRANSFORM(ltFoxtime, '@YS')
Converting the FoxPro datetime back to a Unix timestamp is simply a matter of reversing the above process:
lnTimeStamp = ltFoxTime - DATETIME(1970, 1, 1, 0, 0, 0)
And that's all there is to it. If you need to work with Unix timestamps in your VFP code, these conversions will do the job quickly and easily.
Please note: The information given on this site has been carefully checked and is believed to be correct, but no legal liability can be accepted for its use. Do not use code, components or techniques unless you are satisfied that they will work correctly with your sites or applications.