ios - 如何在swift2中将分钟添加到自定义时间

标签 ios swift

我做的是:

How to add minutes to current time in swift

how to add 30 minutes to current time

enter image description here

这是我的代码:

 endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 let endTimeString = "2017-01-16 12:58:56"
 let endTime = endFormatter.dateFromString(endTimeString)
 endTime?.dateByAddingTimeInterval(180) // 3 Minute
 print(endTime)

第一个回答@rob 我尝试了那个但失败了。第二个答案建议 dateByAddingTimeInterval 我不介意它是否有效。

最佳答案

您需要像@Rob 那样使用dateByAddingUnit 而不是dateByAddingTimeInterval。您没有获得正确时间的原因可能是 TimeZone,因此请尝试使用您的 NSDateFormatter 实例设置 timeZone

endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
endFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)

//Now add the 3 minute in endTime

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateByAddingUnit(.Minute, value: 3, toDate: endTime, options: [])

关于ios - 如何在swift2中将分钟添加到自定义时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41675224/

相关文章:

ios - 我们可以使用 Twilio iOS SDK 进行 VOIP 推送通知吗?

ios - 返回到 ViewController 时未设置 hidesBottomBarWhenPushed

iOS 7 : Selecting a UICollectionViewCell will select cells in the UITableView within it

ios - iPad 上的绘制矩形导致内存问题

ios - 禁用 App Transport Security 和潜在的下层客户端中断

ios - 仅使顶部 ViewController 旋转

ios - UILocalNotification 接收函数在 iOS10 (Swift 3.0) 中弃用

ios - 在 XCode 问题中调试自定义方案

ios - 带有子 UIView(包含内容)的 UIScrollView 未检测到点击

xcode - 如何在 addSubview 之后添加约束,以便 subview 随父 View 调整大小