基本上,就像标题说的那样。我想知道如何添加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.
当前回答
斯威夫特2.0
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
其他回答
在斯威夫特
var dayComponenet = NSDateComponents()
dayComponenet.day = 1
var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
我也有同样的问题;使用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];
}
斯威夫特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 4或Swift 5中,你可以使用like bellow:
let date = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let yesterday_date = dateFormatter.string(from: yesterday!)
print("yesterday->",yesterday_date)
输出:
Current date: 2020-03-02
yesterday date: 2020-03-01
swift 5更新
let nextDate = fromDate.addingTimeInterval(60*60*24)