0

What I do is:

How to add minutes to current time in swift

how to add 30 minutes to current time

enter image description here

Here is my code:

 endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 let endTimeString = "2017-01-16 12:58:56"
 let endTime = endFormatter.dateFromString(endTimeString)
 endTime?.dateByAddingTimeInterval(180) // 3 Minute
 print(endTime)

1st answer @rob i tried that one but failed . second answer suggest dateByAddingTimeInterval i am not suer is it is work or not .

Community
  • 1
  • 1
cristan lika
  • 415
  • 1
  • 7
  • 22

2 Answers2

2

You need to use dateByAddingUnit as @Rob doing instead of dateByAddingTimeInterval. The reason you are not getting correct time is may because of TimeZone so try to set timeZone with your NSDateFormatter instance.

endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
endFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)

//Now add the 3 minute in endTime

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateByAddingUnit(.Minute, value: 3, toDate: endTime, options: [])
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • i accept your answer with in 2 minute could you tell me please why i don't use **dateByAddingTimeInterval** and when need to use **dateByAddingTimeInterval** – cristan lika Jan 16 '17 at 11:33
  • i am not sure .. i did getting any thing there .. could you help just a single line . – cristan lika Jan 16 '17 at 11:43
  • @cristanlika `dateByAddingTimeInterval` will not give you correct date in case of day-light savings where as `dateByAddingUnit` will give you the perfect one. – Nirav D Jan 16 '17 at 11:46
  • 1
    Using `dateByAddingTimeInterval` to add seconds, minutes or even hours is actually no problem. 3 minutes are *always* 180 seconds, no matter what the time zone or calendar is. What the referenced link states is that a day (or month, year, ...) is not a fixed time interval, and *then* you have to do the proper calendar calculations. – But there is no reason to avoid `dateByAddingTimeInterval` completely. – Martin R Jan 16 '17 at 12:14
  • @MartinR Thanks for the clarification :) – Nirav D Jan 16 '17 at 12:17
0
let dateWithMinuteInterval = Calendar.current.date(byAdding: DateComponents(minute: 23), to: endTime)!
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358