基本上,就像标题说的那样。我想知道如何添加1天的NSDate。
如果它是:
21st February 2011
它将变成:
22nd February 2011
或者如果它是:
31st December 2011
它将变成:
1st January 2012.
基本上,就像标题说的那样。我想知道如何添加1天的NSDate。
如果它是:
21st February 2011
它将变成:
22nd February 2011
或者如果它是:
31st December 2011
它将变成:
1st January 2012.
当前回答
Swift 4,如果你真正需要的是24小时轮班(60*60*24秒)而不是“1个日历天”
未来: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
其他回答
只是为了好玩,通过一些扩展和操作符重载,你可以得到一些不错的东西,比如:
let today = Date()
let tomorrow = today + 1.days
, or
var date = Date()
date += 1.months
下面是支持代码:
extension Calendar {
struct ComponentWithValue {
let component: Component
let value: Int
}
}
extension Int {
var days: Calendar.ComponentWithValue {
.init(component: .day, value: self)
}
var months: Calendar.ComponentWithValue {
.init(component: .month, value: self)
}
}
func +(_ date: Date, _ amount: Calendar.ComponentWithValue) -> Date {
Calendar.current.date(byAdding: amount.component, value: amount.value, to: date)!
}
func +(_ amount: Calendar.ComponentWithValue, _ date: Date) -> Date {
date + amount
}
func +=(_ date: inout Date, _ amount: Calendar.ComponentWithValue) {
date = date + amount
}
代码是最少的,并且可以很容易地扩展到允许.月,.年,.小时等。还可以无缝添加对减法(-)的支持。
虽然在+操作符的实现中有一个强制的展开,但是不确定在哪种情况下日历可以返回nil日期。
简单的Swift扩展昨天和明天从任何日期:
extension Date {
var previousDay: Date {
Calendar.current.date(byAdding: DateComponents(day:-1), to: self)!
}
var nextDay: Date {
Calendar.current.date(byAdding: DateComponents(day:+1), to: self)!
}
}
我在这里根据问题中的建议强制展开可选选项: 何时dateByAddingComponents:toDate:options返回nil?
斯威夫特5
let today = Date()
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: today)
objective - c
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// now build a NSDate object for the next day
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: [NSDate date] options:0];
你可以使用NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)秒,其中秒为60 * 60 * 24 = 86400
Swift 5.0:
var dayComponent = DateComponents()
dayComponent.day = 1 // For removing one day (yesterday): -1
let theCalendar = Calendar.current
let nextDate = theCalendar.date(byAdding: dayComponent, to: Date())
print("nextDate : \(nextDate)")
目标C:
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
NSLog(@"nextDate: %@ ...", nextDate);
这应该是不言而喻的。