Set NSDate 0 seconds in swift

aftab ahmed picture aftab ahmed · Apr 22, 2015 · Viewed 9.1k times · Source

I'm trying to get NSDate from UIDatePicker, but it constantly returns me a date time with trailing 20 seconds. How can I manually set NSDate's second to zero in swift?

Answer

George Filippakos picture George Filippakos · Jul 13, 2017
extension Date {

    var zeroSeconds: Date? {
        let calendar = Calendar.current
        let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: self)
        return calendar.date(from: dateComponents)
    }

}

Usage:

let date1 = Date().zeroSeconds

let date2 = Date()
print(date2.zeroSeconds)