How to change the current day's hours and minutes in Swift?

Be aware that for locales that uses Daylight Saving Times, some hours may not exist on the clock change days or they may occur twice. Both solutions below return a Date? and use force-unwrapping. You should handle possible nil in your app.

Swift 3, 4 and iOS 8 / OS X 10.9 or later

let date = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: Date())!

Swift 2

Use NSDateComponents / DateComponents:

let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let components = gregorian.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: now)

// Change the time to 9:30:00 in your locale
components.hour = 9
components.minute = 30
components.second = 0

let date = gregorian.dateFromComponents(components)!

Note that if you call print(date), the printed time is in UTC. It's the same moment in time, just expressed in a different timezone from yours. Use a NSDateFormatter to convert it to your local time.


swift 3 date extension with timezone

extension Date {
    public func setTime(hour: Int, min: Int, sec: Int, timeZoneAbbrev: String = "UTC") -> Date? {
        let x: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
        let cal = Calendar.current
        var components = cal.dateComponents(x, from: self)

        components.timeZone = TimeZone(abbreviation: timeZoneAbbrev)
        components.hour = hour
        components.minute = min
        components.second = sec

        return cal.date(from: components)
    }
}

Tags:

Nsdate

Swift