-2

I want to add minutes to my current time. Here is my code. Thank you

let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
let currentTime = formatter.string(from: Date())
pawello2222
  • 46,897
  • 22
  • 145
  • 209
Paul Addai
  • 59
  • 1
  • 7

2 Answers2

1

Use Calendar.current.date(byAdding:,value:,to:) method.

let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
let currentTime = formatter.string(from: Date())
let tenMinutesLater = Calendar.current.date(byAdding: .minute, value: 10, to: Date())!
print(formatter.string(from: tenMinutesLater))

Or simply:

print(formatter.string(from: Date().addingTimeInterval(10*60)))
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
-1

Try this extension:

 extension Date {
     
    public func addMinute(_ minute: Int) -> Date? {
        var comps = DateComponents()
        comps.minute = minute
        let calendar = Calendar.current
        let result = calendar.date(byAdding: comps, to: self)
        return result ?? nil
    }

 }

Usage: Example I add 10 minutes.

 let originalDate: Date = Date()
 let newDate = originalDate.addMinute(10)
Bunthoeun
  • 143
  • 1
  • 1
  • 11