2

我有一个字符串格式的日期,就像30-11-2012. 我希望它旁边的日期01-12-2012再次以字符串格式显示。有没有办法得到它?

4

3 回答 3

7

您应该使用 NSCalendar 以获得最佳兼容性

NSDate *today = [NSDate dateWithNaturalLanguageString:@"2011-11-30"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [NSDateComponents new];
dayComponent.day = 1;

today = [calendar dateByAddingComponents:dayComponent toDate:today options:0];
//2011-12-01 12:00:00 +0000
于 2012-11-28T06:05:54.370 回答
4

我从一个忘记名字的人那里得到了答案,我正要接受他/她的答案,但是当我点击接受答案时,它告诉我该帖子已被删除。

该匿名人士给出的答案如下

NSString *dateString = @"22-11-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];


NSDateComponents *components= [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *dateIncremented= [calendar dateByAddingComponents:components toDate:dateFromString options:0];

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringFromDate = [myDateFormatter stringFromDate:dateIncremented];
NSLog(@"%@", stringFromDate);

最后,我真的很想感谢那个匿名的人,我知道这并没有那么棘手,但这对我帮助很大。再次感谢匿名助手。

于 2012-11-28T06:59:26.753 回答
-1

迅捷3.0

var components = DateComponents()
components.day = 1
let now = Date()
let futureDate = Calendar.current.date(byAdding: components, to: now, wrappingComponents: false)

//现在 = 2017-03-22 未来日期 = 2017-03-23

于 2017-03-22T09:33:39.647 回答