8

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.

xeo gegry
  • 121
  • 1
  • 3
  • 5

2 Answers2

56

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
Tim Williams
  • 137,250
  • 8
  • 88
  • 114
3

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
J Low
  • 49
  • 1