如何快速将分钟添加到当前时间 [英] How to add minutes to current time in swift

查看:38
本文介绍了如何快速将分钟添加到当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Swift 的新手,正在尝试调度程序.我选择了开始时间,我需要将 5 分钟(或它的倍数)添加到开始时间并将其显示在 UILabel?

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*

推荐答案

两种方法:

  1. 使用日历date(byAdding:to:wrappingComponents:).例如,在 Swift 3 及更高版本中:

  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)

  • 只需使用 + 运算符(请参阅 +(_:_:)) 添加TimeInterval(即一定的秒数).例如.要添加五分钟,您可以:

  • 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.)

    你也可以使用 addingTimeInterval,如果你'd 更喜欢:

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

    let date = startDate.addingTimeInterval(5 * 60)
    

  • 底线,+/addingTimeInterval 对于简单场景来说是最简单的,但是如果您想添加更大的单位(例如,天、月等),您可能想要使用日历计算,因为它们会根据夏令时进行调整,而 addingTimeInterval 不会.

    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.

    对于 Swift 2 版本,请参阅此答案的先前修订版.

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

    这篇关于如何快速将分钟添加到当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆