Search code examples
swiftnsdateuidatepickernscalendar

NSDate and UIDatepicker Swift


I am exercising in Swift, experimenting with Dates.
I made an app that shows the current date, then I add days to that date by inserting them to the NSCalendar component.

All of that works just fine, by adding a day I get the next day. My problem is that I have a UIDatePicker that shows only time. I'm trying to insert the given by me hour and minute but instead I am adding those numbers to the future date because it keeps the same hour and minute as of the current date.

So my questions are:

  • Is there a way to get the current date and then somehow change it's hour and minute values to 0?
  • Is it possible to replace the future time's hour and minute values to the ones that I give through the UIDatePicker?

What I'm trying to accomplish here is to be able to add future events to a calendar at a time that I want to and not at a future date with a time the same as the time I am about to add the event.

Any hints are welcome.


Solution

  • Use NSCalendar class:

    let date = NSDate() // date with current time
    let calendar = NSCalendar.currentCalendar()
    let date2 = calendar.dateBySettingHour(0, minute: 0, second: 0, ofDate: date, options: []) // date with zero time