Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift add 1 week to current date

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)]
like image 453
user3255746 Avatar asked Sep 07 '16 04:09

user3255746


People also ask

How to add 1 day in Date Swift?

Add Days to Current Date To add more days to a current date object, you can use the Calendar and the DateComponents() Swift structs. print(futureDate!) let currentDate = Date() var dateComponent = DateComponents() dateComponent. day = 1 let futureDate = Calendar.

How do I get current week in Swift?

To get the ISO week number (1-53), use calendar. component(. weekOfYear, from: date ) . To get the corresponding four-digit year (e.g. 2022), use calendar.

How do I get the current Date in Xcode?

Use NSDate and NSDateFormatter. NSDate *today = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/yyyy"]; NSString *dateString = [dateFormat stringFromDate:today]; NSLog(@"date: %@", dateString);


2 Answers

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())
like image 97
Rashwan L Avatar answered Sep 28 '22 11:09

Rashwan L


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

Calendar.current.date(byAdding: .weekOfYear, value: 1, to: date)
like image 34
mishimay Avatar answered Sep 28 '22 11:09

mishimay