How to get the number of days between two dates objective-c

I'm trying to make a shortcut that says how many days are left before the event. I want to calculate the difference between today's date and the date of events. I use this code and give me -4600. It works fine until I use today's date.

NSDateFormatter *f = [[NSDateFormatter alloc] init]; [f setDateFormat:@"yyyy-MM-dd"]; NSDate *startDate = [NSDate date]; NSDate *endDate = [f dateFromString:end]; NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:startDate toDate:endDate options:0]; return components.day; return components.day; 
+5
ios objective-c nsdate nsstring
source share
1 answer

By default, [NSDate date] the return date in the format 2013-08-06 08:50:25 +0000 and you set your formatter to yyyy-MM-dd , so you need to convert startDate to yyyy-MM-dd this form.

try it

 NSDateFormatter *f = [[NSDateFormatter alloc] init]; [f setDateFormat:@"yyyy-MM-ddHH:mm:ss ZZZ"]; NSDate *startDate = [NSDate date]; NSLog(@"%@",startDate); NSDate *endDate = [f dateFromString:end]; NSLog(@"%@",endDate); NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:startDate toDate:endDate options:0]; return components.day; 
+17
source share

All Articles