83

If I create a Date() to get the current date and time, I want to create a new date from that but with different hour, minute, and zero seconds, what's the easiest way to do it using Swift? I've been finding so many examples with 'getting' but not 'setting'.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
u84six
  • 4,604
  • 6
  • 38
  • 65
  • Had you try it with `NSDateFormatter`? and use `dateFromString` from it – Lee Mar 18 '16 at 00:51
  • I think this answer is better than converting to string and back again. That's why I asked "easiest way" in my question. I know there are a few ways to do this but I think using the components is best. – u84six Mar 18 '16 at 14:14

3 Answers3

174

Be aware that for locales that uses Daylight Saving Times, on clock change days, some hours may not exist 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+ 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.

Code Different
  • 90,614
  • 16
  • 144
  • 163
34

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)
    }
}
RiceAndBytes
  • 1,286
  • 10
  • 21
4
//Increase the day & hours in Swift

let dateformat = DateFormatter()
let timeformat = DateFormatter()
        
dateformat.dateStyle = .medium
timeformat.timeStyle = .medium

//Increase Day

let currentdate = Date()

let currentdateshow = dateformat.string(from: currentdate)
textfield2.text = currentdateshow

let myCurrentdate = dateformat.date(from: dateTimeString)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myCurrentdate) // Increase 1 Day

let tomorrowday = dateformat.string(from: tomorrow!)
text3.text = tomorrowday
text3.isEnabled = false
  
//increase Time  
    
let time = Date()

let currenttime = timeformat.string(from: time)
text4.text = currenttime
        
let mycurrenttime = timeformat.date(from: currenttime)!
let increasetime = Calendar.current.date(byAdding: .hour, value: 2, to: mycurrenttime) //increase 2 hrs.

let increasemytime = timeformat.string(from: increasetime!)
text5.text = increasemytime