Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Created February 21, 2018 19:06
Show Gist options
  • Save cprovatas/9006597ffe6439941ad0fdb24592c112 to your computer and use it in GitHub Desktop.
Save cprovatas/9006597ffe6439941ad0fdb24592c112 to your computer and use it in GitHub Desktop.
Round Date to Second
extension Date {
var roundedToSecond: Date {
let date = self
let diff = 1000000000 - Calendar.current.component(.nanosecond, from: date)
return Calendar.current.date(byAdding: .nanosecond, value: diff, to: date)!
}
}
/// USAGE:
let roundedDate = Date().roundedToSecond /// zero nanoseconds
@antonjazz
Copy link

FYI This rounds down correctly if you change to the following line:

let diff = -Calendar.current.component(.nanosecond, from: date)

As is, the code adds an extra second.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment