Excel VBA:将日期字符串转换为 Unix 时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12325948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 17:38:18  来源:igfitidea点击:

Excel VBA: Convert a date string to a Unix timestamp

excelvbadatetimestamp

提问by xeo gegry

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.

Excel VBA:如何将日期字符串
“2012-08-20”转换 为时间戳:1345438800
我需要在单元格中存储 1345438800 作为长数据类型值。

回答by Tim Williams

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

回答by J Low

To ensure an accurate complete round trip, add a timestamp to the DateDiff and DateAdd functions:

为确保准确完整的往返行程,请向 DateDiff 和 DateAdd 函数添加时间戳:

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