Excel VBA: Convert a date string to a Unix timestamp
Solution 1:
Date to timestamp:
Public Function toUnix(dt) As Long
toUnix = DateDiff("s", "1/1/1970", dt)
End Function
Timestamp to date:
Public Function fromUnix(ts) As Date
fromUnix = DateAdd("s", ts, "1/1/1970")
End Function
Solution 2:
To ensure an accurate complete round trip, add a timestamp to the DateDiff and DateAdd functions:
Date to timestamp:
Public Function toUnix(dt) As Long
toUnix = DateDiff("s", "1/1/1970 00:00:00", dt)
End Function
Timestamp to date:
Public Function fromUnix(ts) As Date
fromUnix = DateAdd("s", ts, "1/1/1970 00:00:00")
End Function