我遇到了一个问题,我需要在 7 天前创建一个步进器。我为此编写了代码,但如果是一个月的最后几天,它将在同月继续,而不是在下个月也应该更改。 当年需要执行同样的案例。
例如,如果今天是 2016 年 12 月 30 日,那么通过添加 7 天,它需要更改为 2017 年 1 月 7 日。提前致谢。
最佳答案
试试这个。在这里,我从特定日期开始添加了 7 天。
// Enter current date
NSString *currentDate = @"2016-12-30";
// Set number of days to add
int addDaysCount = 7;
// Set date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
// Convert string to NSDate
NSDate *dateFromString = [dateFormatter dateFromString:currentDate];
// Initialize date component
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:addDaysCount];
// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:dateFromString options:0];
NSLog(@"Current date: %@", [dateFormatter stringFromDate:dateFromString]);
NSLog(@"Updated date: %@", [dateFormatter stringFromDate:newDate]);
关于ios - 如果今天是本月的最后一天,如何添加日期。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655058/