8

I am using a datePicker and trying to establish the minimum date as the current date and the maximum being a week from today. I cannot seem to get the max working. Here is my code:

calendarView.minimumDate = todaysDate
calendarView.maximumDate = [todaysDate .dateByAddingTimeInterval(60*60*24*10)]
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
user3255746
  • 1,377
  • 3
  • 12
  • 13

3 Answers3

20

You can do:

let today = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let nextWeek = cal!.dateByAddingUnit(NSCalendar.Unit.Day, value: 7, toDate: today, options: NSCalendar.Options.MatchLast)

This will print out 2016-09-14 04:21:14

Swift 5.x

let calendar = Calendar.current
let addOneWeekToCurrentDate = calendar.date(byAdding: .weekOfYear, value: 1, to: Date())
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • 2
    Never use the first option. It will be wrong in some cases. – rmaddy Sep 07 '16 at 04:29
  • I was looking for a ".week" property, but I guess this works too! –  Jan 13 '19 at 19:50
  • I was concerned if using a different calendar, but apparently almost all calendars have 7 days in a week: https://www.atlasobscura.com/articles/why-cant-we-get-rid-of-the-7day-week – TruMan1 May 07 '19 at 13:34
7

This code works well even if over the year-end.

Calendar.current.date(byAdding: .weekOfYear, value: 1, to: date)
mishimay
  • 4,237
  • 1
  • 27
  • 23
  • Is there any difference in using `.weekOfMonth` instead of `.weekOfYear` in this case? I tried different calendars, locales and timezones but it seems to work fine – fruitcoder Jan 03 '20 at 10:06
2
    extension Date {
    func addWeek(noOfWeeks: Int) -> Date {
    return Calendar.current.date(byAdding: .weekOfYear, value: noOfWeeks, to: self)!
    }
   }
    //USAGE    
    let newDate = Date().addWeek(noOfWeeks: 3)
Pranit
  • 892
  • 12
  • 20