简体   繁体   中英

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?

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)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM