Convert date to next day's date in iOS

2019-04-02 03:23发布

问题:

I have a date in string format just like 30-11-2012. I want the date next to it like 01-12-2012 again in string format. Is there any way of getting it?

回答1:

You should use NSCalendar for best compatibility

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


回答2:

I got the answer by someone I forget the name, I was about to accept his/her answer but when I clicked on accept answer it told me that the post bas been removed.

The answer given by that anonymous person was given below

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);

In the end I really like to thanks that anonymous person, I know this was not as much tricky but this helped me a lot. Thanks again you the Anonymous Helper.



回答3:

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