Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set NSDate 0 seconds in swift

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?

like image 609
aftab ahmed Avatar asked Apr 22 '15 06:04

aftab ahmed


2 Answers

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)
like image 110
George Filippakos Avatar answered Oct 15 '22 18:10

George Filippakos


From this answer in Swift:

var date = NSDate();
let timeInterval = floor(date .timeIntervalSinceReferenceDate() / 60.0) * 60.0
date = NSDate(timeIntervalSinceReferenceDate: timeInterval)
like image 28
Vlad Avatar answered Oct 15 '22 16:10

Vlad