How to add minutes to current time in swift

前端 未结 10 1302
天涯浪人
天涯浪人 2020-11-27 03:10

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?<

相关标签:
10条回答
  • 2020-11-27 03:40

    I think the simplest will be

    let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))
    
    0 讨论(0)
  • 2020-11-27 03:47

    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
    
    0 讨论(0)
  • 2020-11-27 03:49

    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"
    
    0 讨论(0)
  • 2020-11-27 03:50

    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
    
    0 讨论(0)
提交回复
热议问题