Excel 时间戳和时间格式互相转换

一、函数及公式:

1、时间戳转日期时间格式

(1)10位时间戳转日期时间格式(秒)

函数如下:

=TEXT((A1+8*3600)/86400+70*365+19,"yyyy/mm/dd hh:mm:ss")

(2)13位时间戳转日期时间(毫秒)

=TEXT((A1/1000+8*3600)/86400+70*365+19,"yyyy/mm/dd hh:mm:ss")

如对日期有格式要求,可替换函数中的日期格式字符串"yyyy/mm/dd hh:mm:ss"为要求格式。

2、日期时间转时间戳

日期时间转10位时间戳(秒)

函数如下:

= LONG((A2-70*365-19)86400-83600)

二、VBA函数【原始代码都是以1970-01-01 00:00:00为起始点,因为我们是北京时间,所以有修改】:

1、日期时间格式转10位时间戳:

Public Function toUnix(dt) As Long
    toUnix = DateDiff("s", "1970-01-01 08:00:00", dt)
   '或者这个格式 toUnix = DateDiff("s", "1/1/1970 08:00:00", dt)
End Function

或者

Function DateTimeToTimestamp(dt As Date) As Double
    DateTimeToTimestamp = IIf(Not IsEmpty(dt), (dt - #1/1/1970 8:00:00 AM#) * 86400, Null)    
End Function

如果需要格式化为文本,则toUnix = Format( toUnix, "0")

2、日期时间格式转13位时间戳:

直接在10位的结果基础上乘以1000即可,但一般不需要到微秒。

3、10位时间戳转为日期时间格式 :

Function UnixToDateTime(unixTime As Double) As Date
    UnixToDateTime = DateAdd("s", unixTime, "1970-01-01 08:00:00")
End Function

4、13位时间戳转为日期时间格式 :

Function TimestampToDate(timestamp As Double) As Date
    ' Unix纪元到现在的秒数(13位时间戳是以毫秒为单位,所以除以1000)
    Dim seconds As Double
    seconds = timestamp / 1000
    
    ' 将秒数转换为日期时间
    TimestampToDate = DateAdd("s", seconds, "1970-01-01 08:00:00")
End Function

或者【测试有点问题】

Function TimestampToDate(timestamp As Double) As Date
    ' 13位时间戳是以毫秒为单位的,所以我们从1970年1月1日开始
    ' 注意:VBA中的时间戳可能会有一天的偏差,因为VBA认为1900年1月1日是一天的开始
    Dim startTime As Date
    startTime = "1970-01-01"
 
    ' 将时间戳转换为毫秒,并从1970年1月1日开始计算
    TimestampToDate = DateAdd("ms", timestamp, startTime)
End Function