How to add minutes to current time in swift

IosSwiftDate

Ios Problem Overview


I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel?

@IBAction func timePickerClicked(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
    var dateStr = dateFormatter.stringFromDate(startTime.date)
    let sttime = dateStr
    startTimeDisplay.text = dateStr
}

// How to advance time by 5 minutes for each section based on the   start time selected and display time 
// section 1 = start time + 5
// section 2 = start time + 10*

Ios Solutions


Solution 1 - Ios

Two approaches:

  1. Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later:

     let calendar = Calendar.current
     let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
    
  2. Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes, you can:

     let date = startDate + 5 * 60
    

(Note, the order is specific here: The date on the left side of the + and the seconds on the right side.)

You can also use addingTimeInterval, if you’d prefer:

    let date = startDate.addingTimeInterval(5 * 60)

Bottom line, +/addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn’t.


For Swift 2 renditions, see the previous revision of this answer.

Solution 2 - Ios

You can use Calendar's method

func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?

to add any Calendar.Component to any Date. You can create a Date extension to add x minutes to your UIDatePicker's date:

Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0

extension Date {
    func adding(minutes: Int) -> Date {
        return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
    }
}

Then you can just use the extension method to add minutes to the sender (UIDatePicker):

let section1 = sender.date.adding(minutes: 5)
let section2 = sender.date.adding(minutes: 10)

Playground testing:

Date().adding(minutes: 10)  //  "Jun 14, 2016, 5:31 PM"

Solution 3 - Ios

Swift 4:

// add 5 minutes to date

let date = startDate.addingTimeInterval(TimeInterval(5.0 * 60.0))

// subtract 5 minutes from date

let date = startDate.addingTimeInterval(TimeInterval(-5.0 * 60.0))

Swift 5.1:

// subtract 5 minutes from date
transportationFromDate.addTimeInterval(TimeInterval(-5.0 * 60.0))

Solution 4 - Ios

You can use in swift 4 or 5

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let current_date_time = dateFormatter.string(from: date)
    print("before add time-->",current_date_time)
    
    //adding 5 miniuts
    let addminutes = date.addingTimeInterval(5*60)
    dateFormatter.dateFormat = "yyyy-MM-dd H:mm:ss"
    let after_add_time = dateFormatter.string(from: addminutes)
    print("after add time-->",after_add_time)

output:

before add time--> 2020-02-18 10:38:15
after add time--> 2020-02-18 10:43:15

Solution 5 - Ios

extension Date {
    func withAddedMinutes(minutes: Double) -> Date {
         addingTimeInterval(minutes * 60)
    }

    func withAddedHours(hours: Double) -> Date {
         withAddedMinutes(minutes: hours * 60)
    }
}

useCase

let anHourFromNow = Date().withAddedHours(hours: 1)
let aMinuteFromNow = Date().withAddedMinutes(minutes: 1)

Solution 6 - Ios

You can do date arithmetic by using NSDateComponents. For example:

import Foundation

let comps = NSDateComponents()

comps.minute = 5

let cal = NSCalendar.currentCalendar()

let r = cal.dateByAddingComponents(comps, toDate: NSDate(), options: nil)

It is what you see when you try it in playground

enter image description here

Solution 7 - Ios

NSDate.init with timeIntervalSinceNow:
Ex:

 let dateAfterMin = NSDate.init(timeIntervalSinceNow: (minutes * 60.0))

Solution 8 - Ios

Save this little extension:

extension Int {

 var seconds: Int {
    return self
 }

 var minutes: Int {
    return self.seconds * 60
 }

 var hours: Int {
    return self.minutes * 60
 }

 var days: Int {
    return self.hours * 24
 }

 var weeks: Int {
    return self.days * 7
 }

 var months: Int {
    return self.weeks * 4
 }

 var years: Int {
    return self.months * 12
 }
}

Then use it intuitively like:

let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)

Solution 9 - Ios

Swift 3:

let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes

Solution 10 - Ios

I think the simplest will be

let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))

Solution 11 - Ios

In case you want unix timestamp

        let now : Date = Date()
        let currentCalendar : NSCalendar = Calendar.current as NSCalendar
        
        let nowPlusAddTime : Date = currentCalendar.date(byAdding: .second, value: accessTime, to: now, options: .matchNextTime)!

        let unixTime = nowPlusAddTime.timeIntervalSince1970

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontry maadeeView Question on Stackoverflow
Solution 1 - IosRobView Answer on Stackoverflow
Solution 2 - IosLeo DabusView Answer on Stackoverflow
Solution 3 - IosGilad BrunfmanView Answer on Stackoverflow
Solution 4 - IosEnamul HaqueView Answer on Stackoverflow
Solution 5 - IosMuhamad Jawdat Salem AkoumView Answer on Stackoverflow
Solution 6 - IosAnthony KongView Answer on Stackoverflow
Solution 7 - IosKumar KLView Answer on Stackoverflow
Solution 8 - IosFitsyuView Answer on Stackoverflow
Solution 9 - IosAl___View Answer on Stackoverflow
Solution 10 - IosSachin NautiyalView Answer on Stackoverflow
Solution 11 - IosPradeep Kumar KushwahaView Answer on Stackoverflow