简体   繁体   English

Swift:计算两个日期之间的时间

[英]Swift: Calculate time between two dates

I have a text field in my storyboard and have created the following outlet in the corresponding ViewController: 我的情节提要中有一个文本字段,并在相应的ViewController中创建了以下出口:

@IBOutlet weak var birthday: UITextField!

The user will put in their month and day in "MM/DD" format and then press enter. 用户将以“ MM / DD”格式输入其月份和日期,然后按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. 如果要提供textFiled选项,请使用UIPickerView(.date)输入日期,以使用户不会弄乱格式。 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)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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