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

If I create Date() to get the current date and time, I want to create a new date from this, but with different hours, minutes and zero seconds, what is the easiest way to do this with Swift? I have found so many examples with โ€œreceivingโ€ but not โ€œtuningโ€.

+20
swift nsdate
source share
2 answers

Remember that in regions where daylight saving time is used, some watches may not exist on the days of the change of hours or they may occur twice. Both solutions below return Date? and use unboxing by force. You must handle a possible nil in your application.

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)! 

Please note that if you call print(date) , the print time is in UTC. This is the same point in time, simply expressed in a different time zone from yours. Use NSDateFormatter to convert it to your local time.

+57
source share

quick extension of date 3 with time zone

 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) } } 
+21
source share

All Articles