This question already has an answer here:
Hi Im trying to work out the time between two dates using UIpickers and I am lost. I cannot fathom where to go to on this to get the value to plug into the label. Im not sure if I should use components or before the comparison or just after to put it in the label. Thanks for any pointers.
let calendar = NSCalendar.currentCalendar()
let userCalendar = NSCalendar.currentCalendar()
// Set up date object
let DateMakerFormatter = NSDateFormatter()
let date = NSDate()
@IBOutlet weak var toDatePicker: UIDatePicker!
@IBOutlet weak var fromDatePicker: UIDatePicker!
@IBOutlet weak var dayYearLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func toDatePickerAction(sender: UIDatePicker) {
var DateFormatter = NSDateFormatter()
DateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
var endTime = DateFormatter.stringFromDate(toDatePicker.date)
self.dayYearLabel.text = endTime
var targetDate = endTime
println("\(endTime)")
}
@IBAction func fromDatePickerAction(sender: UIDatePicker) {
var fromDateFormatter = NSDateFormatter()
fromDateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
var startTime = fromDateFormatter.stringFromDate(fromDatePicker.date)
self.dayYearLabel.text = startTime
var targetDate2 = startTime
println("\(startTime)")
}
@IBAction func getTheDateButton(sender: AnyObject) {
let calendar = NSCalendar.currentCalendar()
let datecomponents = calendar.components(NSCalendarUnit.CalendarUnitSecond,
fromDate: startTime, toDate: endTime, options: nil)
let second = datecomponents.second
let minute = datecomponents.minute
let hour = datecomponents.hour
let day = datecomponents.day
let year = datecomponents.year
println("Seconds: \(second)")
println("minutes: \(minute)")
println("hours: \(hour)")
println("days: \(day)")
println("years: \(year)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This could be done in a much simpler way:
Then just round the values up. Your UIDatePicker already returns a
NSDate
object. No need to use a date formatter unless you want to print/use the dates in a certain format.You should try using some extensions to help you organize your code. Assuming that you have copied those extensions from the link above, you can do as follow:
As I mentioned here are the extensions from the link above:
And you should create another 4 extensions, one for formatting your date as desired, another one to add a calendar unit to your NSDate and two more to zero the seconds and nanoseconds from the date returned by the date pickers: