0

I'm building an app that calculates the number of days between two dates. When I print the result to the console I get some code included which I want to remove from the result:

enter image description here

I'm trying to remove the unwanted code by splitting the string, using 'componentsSeparatedByString'.

However, in order to use this method I have to first convert the 'components' constant to an NSString. When I try to do this I get an error message: Cannot invoke initializer for type 'NSString' with an argument list of type '(string: NSDateComponents)'

@IBAction func calculateDays(sender: AnyObject) {

    let start = String(firstSelectedDate.text!)
    let end = String(secondSelectedDate.text!)

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"

    let startDate:NSDate = dateFormatter.dateFromString(start)!
    let endDate:NSDate = dateFormatter.dateFromString(end)!

    let cal = NSCalendar.currentCalendar()
    let unit:NSCalendarUnit = NSCalendarUnit.NSDayCalendarUnit

    let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: [])


    let newComponents = NSString(string: components) // Cannot invoke initializer for type 'NSString' with an argument list of type '(string: NSDateComponents)'

    let componentsArray = newComponents?.componentsSeparatedByString("<NSDateComponents: 0x7f91aaf29980>")

    print(componentsArray[1])

Would be very grateful if someone can tell me what I'm doing wrong.

Thanks in advance!

1 Answer 1

1

After you get the components variable you can retrieve the day property, try this instead:

let start = "2010-09-01"
let end = "2010-09-08"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!

let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
print(components.day) // 7

I hope this help you.

Sign up to request clarification or add additional context in comments.

1 Comment

Solved the problem. Thank you so much, Victor!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.