Search code examples
iosswiftnscalendar

Swift: Calculate time between two dates


I have a text field in my storyboard and have created the following outlet in the corresponding ViewController:

@IBOutlet weak var birthday: UITextField!

The user will put in their month and day in "MM/DD" format and then press enter. I want to be able to calculate the number of days since their birthday (not including today) and then use that number in an equation.

How do I calculate the range?


Solution

  • If you are providing the textFiled option use, UIPickerView (.date) to input the date so that user does not mess up with the format. Then use the following code to get the date from input to current date :-

        let calendar: NSCalendar = NSCalendar.currentCalendar()
    
        let firstDate  = NSDate() // Current date
        let dateString = "06-10-2016"// Get input(date) from textfield
    
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
    
        let secondDate = dateFormatter.dateFromString(dateString)
    
    
        let date1 = calendar.startOfDayForDate(firstDate)
        let date2 = calendar.startOfDayForDate(secondDate!)
    
        let flags = NSCalendarUnit.Day
        let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])
        print("amount of days \(components.day)")