基本上,就像标题说的那样。我想知道如何添加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 2.1.1和xcode 7.1 OSX 10.10.5中,你可以使用函数添加任意数量的天数
func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
let dateComponents = NSDateComponents()
let CurrentCalendar = NSCalendar.currentCalendar()
let CalendarOption = NSCalendarOptions()
dateComponents.day = NumberOfDaysToAdd
let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
return newDate!
}
函数调用,将当前日期增加9天
var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)
函数调用,将当前日期减少80天
newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
print(newDate)
其他回答
swift 5更新
let nextDate = fromDate.addingTimeInterval(60*60*24)
斯威夫特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];
对于swift 2.2:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: NSCalendarOptions.MatchStrictly)
希望这能帮助到一些人!
Swift 4.0(在这个精彩的答案中与Swift 3.0相同,只是为了让像我这样的新手清楚)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
它的工作原理!
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitDay;
NSInteger value = 1;
NSDate *today = [NSDate date];
NSDate *tomorrow = [calendar dateByAddingUnit:unit value:value toDate:today options:NSCalendarMatchStrictly];