1

I have some events for which I need to calculate NSDates. For example I'm trying to get the next Monday at 8:00 AM. So I tried some stuff but nothing works:

1.

let nextMonday = NSCalendar.currentCalendar().dateBySettingUnit(NSCalendarUnit.Weekday, value: 2, ofDate: startDate, options: NSCalendarOptions.MatchNextTime)
let nextMondayEight = NSCalendar.currentCalendar().dateBySettingUnit(NSCalendarUnit.Hour, value: 8, ofDate: nextMonday!, options: NSCalendarOptions.MatchNextTime)

I get:

2016-04-12 05:00:00 +0000

That's Tuesday at 8:00 (the time difference is my local time GMT -3).

2.

let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let comp = NSCalendar.currentCalendar().components(unitFlags, fromDate: NSDate())
comp.timeZone = NSTimeZone.localTimeZone()
comp.weekday = 1
comp.hour = 8
comp.minute = 0
comp.second = 0
let compDate = NSCalendar.currentCalendar().dateFromComponents(comp)

print("time: \(compDate!)")

I get:

2016-04-11 05:00:00 +0000

That's today at 8:00 and not next Monday at 8:00.


Any suggestions? Thanks

Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
ilan
  • 4,402
  • 6
  • 40
  • 76
  • I found a similar post that may help: http://stackoverflow.com/questions/18148224/get-next-monday-date-in-ios – Pankaj Apr 11 '16 at 09:15
  • For the first approach, you need to check whether the first day of `NSCalendar.currentCalendar()` is Monday or Sunday – zc246 Apr 11 '16 at 09:22

1 Answers1

5

NSCalendar has a method nextDateAfterDate:matchingComponents:options for this kind of date math.

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.hour = 8 // 8:00
components.weekday = 2 // Monday in Gregorian Calendar

let nextMondayEightOClock = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchStrictly)
vadian
  • 274,689
  • 30
  • 353
  • 361