Created
January 13, 2021 02:16
-
-
Save dduan/58499632798e9cc53f5d7c6a09678310 to your computer and use it in GitHub Desktop.
Convert date components (per RFC3339) to seconds since 1970-01-01
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func toTimestamp(year: Int, month: Int, day: Int, hour: Int, minute: Int, seconds: Int, nanoseconds: Int, offsetInSeconds: Int) -> Double { | |
var year = year | |
year -= month <= 2 ? 1 : 0 | |
let era = (year >= 0 ? year : year - 399) / 400 | |
let yoe = year - era * 400 | |
let doy = (153*(month + (month > 2 ? -3 : 9)) + 2)/5 + day - 1 | |
let doe = yoe * 365 + yoe/4 - yoe/100 + doy | |
let dayCounts = era * 146097 + doe - 719468 | |
let seconds = dayCounts * 86400 + hour * 3600 + minute * 60 + seconds - offsetInSeconds | |
return Double(seconds) + Double(nanoseconds) / 1_000_000_000 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment