Created
February 21, 2018 19:06
-
-
Save cprovatas/9006597ffe6439941ad0fdb24592c112 to your computer and use it in GitHub Desktop.
Round Date to Second
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.