Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a future date in swift with NSDate()

I'm getting an error: "Missing argument for parameter 'coder' in call" for the following code:

var components = NSDateComponents()     
components.setValue(1,forComponent: NSCalendarUnit.CalendarUnitMonth);
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components,       toDate: NSDate(),options:0)

The docs calls for:

NSCalendar.currentCalendar().dateByAddingComponents(<#comps: NSDateComponents?#>, toDate: <#NSDate?#>, options: <#NSCalendarOptions#>)

Can anyone see what I'm missing? I don't see a parameter named 'coder' required.

like image 419
krisacorn Avatar asked Jul 14 '14 16:07

krisacorn


2 Answers

how it looks to be with

swift 4.x

let date = Date()
var components = DateComponents()
components.setValue(1, for: .month)
let expirationDate = Calendar.current.date(byAdding: components, to: date)

swift 2.0

let components: NSDateComponents = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.Month);
let date: NSDate = NSDate()
let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))

swift 1.2

var components = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitMonth);
let date: NSDate = NSDate()
var expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(0))

Objective-C

NSDate *date = [NSDate new];  
NSDateComponents *components = [NSDateComponents new];
components.month = 1;
NSDate *expirationDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:0];
like image 175
holex Avatar answered Nov 15 '22 14:11

holex


Syntax for Swift 3

var components = DateComponents()
components.setValue(1, forComponent: .month)
let date: Date = Date()
let expirationDate = Calendar.current.date(byAdding: components, to: date, options: [])
like image 12
Luke Bartolomeo Avatar answered Nov 15 '22 12:11

Luke Bartolomeo