简体   繁体   English

如何快速将分钟添加到当前时间

[英]How to add minutes to current time in swift

I am new to Swift and am trying a scheduler.我是 Swift 的新手,正在尝试调度程序。 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 ?我选择了开始时间,我需要将 5 分钟(或它的倍数)添加到开始时间并将其显示在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*

Two approaches:两种做法:

  1. Use Calendar and date(byAdding:to:wrappingComponents:) .使用Calendardate(byAdding:to:wrappingComponents:) Eg, in Swift 3 and later:例如,在 Swift 3 及更高版本中:

     let calendar = Calendar.current let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
  2. Just use + operator (see +(_:_:) ) to add a TimeInterval (ie a certain number of seconds).只需使用+运算符(见+(_:_:) )来添加一个TimeInterval (即一定的秒数)。 Eg 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:如果您愿意,也可以使用addingTimeInterval

     let date = startDate.addingTimeInterval(5 * 60)

Bottom line, + / addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (eg, days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn't.addingTimeInterval是,对于简单的场景, + / addingTimeInterval是最简单的,但是如果您想添加更大的单位(例如,天、月等),您可能希望使用日历计算,因为它们会根据夏令时进行调整,而addingTimeInterval没有。


For Swift 2 renditions, see the previous revision of this answer .对于 Swift 2 版本,请参阅此答案先前修订版

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 .将任何Calendar.Component添加到任何Date You can create a Date extension to add x minutes to your UIDatePicker 's date:您可以创建一个 Date 扩展来为UIDatePicker的日期添加 x 分钟:

Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0 Xcode 8 和 Xcode 9 • Swift 3.0 和 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):然后你可以使用扩展方法向发件人添加分钟(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"

Swift 4 :斯威夫特 4

// add 5 minutes to date // 添加 5 分钟到日期

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

// subtract 5 minutes from date // 从日期中减去 5 分钟

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

Swift 5.1:斯威夫特 5.1:

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

You can use in swift 4 or 5您可以在 swift 4 或 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

You can do date arithmetic by using NSDateComponents .您可以使用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这是你在操场上尝试时看到的

在此处输入图片说明

NSDate.init with timeIntervalSinceNow : NSDate.inittimeIntervalSinceNow
Ex:前任:

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

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)

Swift 3:斯威夫特 3:

let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes
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)

In case you want unix timestamp如果你想要 unix 时间戳

        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

我认为最简单的将是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM