extension Date {
/// Returns a Date with the specified amount of components added to the one it is called with
func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
return Calendar.current.date(byAdding: components, to: self)
}
/// Returns a Date with the specified amount of components subtracted from the one it is called with
func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
}
}
按OP的要求仅添加一天的用法将是:
let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)
func addUnitToDate(unitType: NSCalendarUnit, number: Int, date:NSDate) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(
unitType,
value: number,
toDate: date,
options: NSCalendarOptions(rawValue: 0))!
}
print( addUnitToDate(.Day, number: 1, date: NSDate()) ) // Adds 1 Day To Current Date
print( addUnitToDate(.Hour, number: 1, date: NSDate()) ) // Adds 1 Hour To Current Date
print( addUnitToDate(.Minute, number: 1, date: NSDate()) ) // Adds 1 Minute To Current Date
// NOTE: You can use negative values to get backward values too
24 回答
Swift 4,如果您真正需要的是24小时轮班(60 * 60 * 24秒)而不是“1个日历日”
未来:
let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去:
let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
使用以下代码:
如
现已弃用 .
对于swift 2.2:
希望这有助于某人!
这应该是不言自明的 .
从iOS 8开始你可以使用
NSCalendar.dateByAddingUnit
Swift 1.x中的示例:
Swift 2.0:
Swift 3.0:
试试这个
iOS 8,OSX 10.9,Objective-C
在swift中,您可以在NSDate中进行扩展以添加方法
你可以用它作为
基于highmaintenance's回答和vikingosegundo's评论工作 Swift 3 & 4 implementation . 此日期扩展还包含更改年,月和时间的其他选项:
按OP的要求仅添加一天的用法将是:
使用以下函数并使用days paramater获取日期daysAhead / daysBehind只是将参数传递为将来日期的正数或以前日期的负数:
Swift 4.0 (与this wonderful answer中的Swift 3.0相同,只是让我觉得像我这样的新手)
在迅速
Swift 3.0非常简单的实现方式是:
这是工作!
你可以使用NSDate的方法
- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
,其中seconds
将是60 * 60 * 24 = 86400
在Swift 2.1.1和xcode 7.1 OSX 10.10.5中,您可以使用函数向前和向后添加任意天数
函数调用将当前日期递增9天
函数调用减少当前日期80天
这是一种通用方法,可让您在指定日期添加/减去任何类型的单位(年/月/日/小时/秒等) .
使用 Swift 2.2
好的 - 我认为这对我有用 . 但是,如果您使用它来添加一天到2013年3月31日,它将返回一个仅添加23小时的日期 . 它实际上可能有24,但在计算中使用只增加了23:00小时 .
同样,如果您向前推进至2013年10月28日,则代码会增加25小时,从而导致日期时间为2013-10-28 01:00:00 .
很奇怪 .
为了增加一天,我在顶部做了一件事,添加:
但这对于某些日期来说真是一团糟,主要是因为夏令时 .
Objective-C,日期是一场噩梦 .
我有同样的问题;使用NSDate的扩展名:
Swift 2.0
Swift 3+ : Try this common extension