Skip to content

Instantly share code, notes, and snippets.

@dduan
Created January 13, 2021 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dduan/58499632798e9cc53f5d7c6a09678310 to your computer and use it in GitHub Desktop.
Save dduan/58499632798e9cc53f5d7c6a09678310 to your computer and use it in GitHub Desktop.
Convert date components (per RFC3339) to seconds since 1970-01-01
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