Search code examples
iosswiftnsdateuilocalnotification

Convert formatted date to NSDate


I have an app that displays a tableview of times in the day (oceanic tides). What I want to do is be able to tap on a time and schedule a local notification to fire at that time.

If I print out the date when I tap the cell I get "5/18/2016 03:31 AM". However, if I pass that in as the fireDate object, then the fireDate of the notification is "nil"

If I simply create an NSDate object to fire 15 seconds after tapping the cell, then the fireDate is: "Wednesday, May 18, 2016 at 2:14:11 PM"

So I guess the real question is, how can I convert "5/18/2016 03:31 AM" to "Wednesday, May 18, 2016 at 3:31:00 AM"?

Thank you!


Solution

  • You need to use a NSDateFormatter for formatting the date to the desired output. Here is how you can do that

    let formatter = NSDateFormatter()
    formatter.dateStyle = NSDateFormatterStyle.FullStyle
    let dateToFire = formatter.dateFromString(datefromcell) //datefromcell is a string that contains the date you got from tapping the tableview cell
    

    For more information on how to format dates, see this link

    Hope this helps. :)