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
  • 37,198
  • 7
  • 99
  • 103
user3255746
  • 1,297
  • 2
  • 11
  • 13

3 Answers3

19

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
  • 37,198
  • 7
  • 99
  • 103
6

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

Calendar.current.date(byAdding: .weekOfYear, value: 1, to: date)
mishimay
  • 4,099
  • 1
  • 24
  • 22
  • 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
  • 852
  • 10
  • 18