无需使用内置日期组件即可将日期转换为自 1970 年以来的时间间隔的公式

问题描述 投票:0回答:0

月、日、时、分、秒。我不想使用

DateComponents
转换这些时间间隔并将其转换回 Unix 时间戳。相反,我只需要使用数学公式进行计算。

试过的代码:

let year: UInt16 = 2023
let month: UInt8 = 2
let date: UInt8 = 16

let hour: UInt8 = 9
let minute: UInt8 = 15
let second: UInt8 = 0

let interval = (UInt64(year) - 1970) * 31536000             // 1 year = 31536000 seconds
                  + UInt64(month-1) * 2678400               // 1 month = 2678400 seconds (average)
                  + UInt64(date) * 86400                    // 1 day = 86400 seconds
                  + UInt64(hour) * 3600                     // 1 hour = 3600 seconds
                  + UInt64(minute) * 60                     // 1 minute = 60 seconds
                  + UInt64(second)

print("Interval: \(interval)") // 1675502100

此代码有效,但时间不正确。对于我给出的时间,时间间隔是 2023 年 2 月 4 日星期六 9:15:00 AM,这是错误的日期但正确的时间。我该如何解决这个问题?

这只是数学公式问题。因此,欢迎使用任何编程语言或纯数学解决方案。

swift date datetime unix-timestamp data-conversion
© www.soinside.com 2019 - 2024. All rights reserved.