基本上,就像标题说的那样。我想知道如何添加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 3.0非常简单的实现将是:
func dateByAddingDays(inDays: Int) -> Date {
let today = Date()
return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}
其他回答
Swift 4,如果你真正需要的是24小时轮班(60*60*24秒)而不是“1个日历天”
未来: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
使用以下代码:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
As
addTimeInterval
现在已弃用。
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);
这应该是不言而喻的。
Swift 3.0非常简单的实现将是:
func dateByAddingDays(inDays: Int) -> Date {
let today = Date()
return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}
我也有同样的问题;使用NSDate扩展:
- (id)dateByAddingYears:(NSUInteger)years
months:(NSUInteger)months
days:(NSUInteger)days
hours:(NSUInteger)hours
minutes:(NSUInteger)minutes
seconds:(NSUInteger)seconds
{
NSDateComponents * delta = [[[NSDateComponents alloc] init] autorelease];
NSCalendar * gregorian = [[[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian] autorelease];
[delta setYear:years];
[delta setMonth:months];
[delta setDay:days];
[delta setHour:hours];
[delta setMinute:minutes];
[delta setSecond:seconds];
return [gregorian dateByAddingComponents:delta toDate:self options:0];
}