WebRuin WebRuin - 4 years ago 182
Swift Question

How can I extract number of years, months, and days since a date in Swift

How can I extract number of years, months, and days since a date in Swift.

So far I have the follow code in a class file named

DatePickerController
.

class DatePickerController: UIViewController {

@IBOutlet var datePicker:UIDatePicker!
@IBOutlet var dateDisplay: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func datePickerChanged(sender: AnyObject) {
setDate()
}

let dateFormatter = NSDateFormatter()

// MARK: - Date Format
func setDate() {
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateDisplay.text = dateFormatter.stringFromDate(datePicker.date)
}

}


I will create separate
UILables
for year, month, and day right.

Answer Source

Like you said, you will need UILabel's for each of the date components. You can then extract the components using custom date formatting strings instead of using NSDateFormatterStye.ShortStyle. This gives you the most flexibility. The formatting strings follow a unicode standard.

I can't test the code in the context of your project, but if you add the labels and connect them correctly to Xcode, I believe that this code will do exactly what you want:

class DatePickerController: UIViewController {

  @IBOutlet var datePicker:UIDatePicker!
  @IBOutlet var dayDisplay: UILabel!
  @IBOutlet var monthDisplay: UILabel!
  @IBOutlet var yearDisplay: UILabel!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  @IBAction func datePickerChanged(sender: AnyObject) {
    setDate()
  }

  let dateFormatter = NSDateFormatter()

  // MARK: - Date Format
  func setDate() {
    dateFormatter.dateFormat = "dd"
    dayDisplay.text = dateFormatter.stringFromDate(datePicker.date)
    dateFormatter.dateFormat = "MM"
    monthDisplay.text = dateFormatter.stringFromDate(datePicker.date)
    dateFormatter.dateFormat = "yyyy"
    yearDisplay.text = dateFormatter.stringFromDate(datePicker.date)
  }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download