我有一个字符串格式的日期,就像30-11-2012
一样。我希望它旁边的日期再次为01-12-2012
字符串格式。
有没有办法得到它?
答案 0 :(得分: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
答案 1 :(得分: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);
最后我真的要感谢那个匿名的人,我知道这并不是那么棘手,但这对我帮助很大。再次感谢Anonymous Helper。
答案 2 :(得分:-1)
swift 3.0
var components = DateComponents()
components.day = 1
let now = Date()
let futureDate = Calendar.current.date(byAdding: components, to: now, wrappingComponents: false)
// now = 2017-03-22 futureDate = 2017-03-23