我使用过此代码,但输出日期不正确。
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSDate * currDate = [NSDate date];
答案 0 :(得分:0)
Here is sample code which uses for date difference.
Main problem is your date format causes the problem i.e 'hh' replace with 'HH'.
NSString *pastDate=@"2016-03-15 01:12:30";
NSDateFormatter *dateformat=[[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *datefor=[dateformat dateFromString:pastDate];
NSString *dateStr=[dateformat stringFromDate:datefor];
NSDate *datetype=[dateformat dateFromString:dateStr];
NSDate *currentDate = [NSDate date];
NSDateComponents *components;
NSInteger days;
components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay
fromDate: datetype toDate: currentDate options: 0];
days = [components day];
NSLog(@"There are %ld days in between the two dates.", (long)days);
May this helps.