How to add minutes to current time in swift

前端 未结 10 1356
天涯浪人
天涯浪人 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: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"
    

提交回复
热议问题