SwiftyJD SwiftyJD - 1 year ago 80
Swift Question

How to add an Int to a NSDate?

I'm currently getting JSON data for a date in this format:

Date = "2016-07-21T18:32:24.347Z"

I need to be able to add an Int, or float that represents minutes (60 min total)

How can I do this?

Answer Source

So there are like a million different ways that you could do this but that is probably not what you are looking for here. The best way to play with these things would be in a playground that way you can see how the changes to your code effect the end result.

So first you need a function that can take a string as a parameter.

func dateFromJSON(dateString: String?) -> NSDate? {}

This Function will take in our string and return us a NSDate

Then we need a date formatter, There are many different ways you can format a date and you can check out the documentation on them here NSDateFormatter Documentation

so here is an example of a formatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ" you can see pretty quickly that different parts refer to differnt peices of a date. IE the yyyy is for the year in this case will give us something like 2016. If it were yy we would only get 16.

Initialize the dateFormatter then apply our format.

You should also throw in some checks to make your code safe. So it should look like this.

func dateFromWebJSON(dateString: String?) -> NSDate? {
   guard let dateString = dateString else {
    return nil
  let formatter = NSDateFormatter()
  let date = ["yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"].flatMap { (dateFormat: String) -> NSDate? in
    formatter.dateFormat = dateFormat
    return formatter.dateFromString(dateString)

  assert(date != nil, "Failed to convert date")
  return date

so now we can call

let time = dateFromWebAPIString(date)
print(time) //  Jul 21, 2016, 12:32 PM

Now to add time you have to remember that 1 NSTimeInterval is 1 second. So do some basic math

let min = 60
let hr = 60 * min

then we can add as much time as you want

 let newTime = time?.dateByAddingTimeInterval(NSTimeInterval(20 * min))
 print(newTime) //  "Jul 21, 2016, 12:52 PM"

20 min later. Hope this helps

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