Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA: Convert a date string to a Unix timestamp

Excel VBA: How to convert date string
"2012-08-20" to timestamp: 1345438800
I need to store 1345438800 in cell as long data type value.

like image 368
xeo gegry Avatar asked Sep 07 '12 21:09

xeo gegry


2 Answers

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
like image 141
Tim Williams Avatar answered Oct 04 '22 04:10

Tim Williams


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
like image 25
J Low Avatar answered Oct 04 '22 03:10

J Low