我想找到两个日期之间的总天数.
例如今天是01-01-2011(DD-MM-YYYY),第二个日期是(25-03-2011),我怎样才能找到总天数?
NSDate *currentdate=[NSDate date]; NSLog(@"curretdate is ==%@",currentdate); NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease]; [tempFormatter1 setDateFormat:@"dd-mm-YYYY hh:mm:ss"]; NSDate *toDate = [tempFormatter1 dateFromString:@"20-04-2011 09:00:00"]; NSLog(@"toDate ==%@",toDate);
解决方法
在你的日期格式你设置错误它是dd-MM-yyyy HH:mm:ss.可能是那个问题..你得到错误的日期而没有得到答案我发送litte位代码获得一天的差异.
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease]; [tempFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"]; NSDate *startdate = [tempFormatter dateFromString:@"15-01-2011 09:00:00"]; NSLog(@"startdate ==%@",startdate); NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease]; [tempFormatter1 setDateFormat:@"dd-MM-yyyy HH:mm:ss"]; NSDate *toDate = [tempFormatter1 dateFromString:@"20-01-2011 09:00:00"]; NSLog(@"toDate ==%@",toDate); int i = [startdate timeIntervalSince1970]; int j = [toDate timeIntervalSince1970]; double X = j-i; int days=(int)((double)X/(3600.0*24.00)); NSLog(@"Total Days Between::%d",days);
编辑1:
我们可以使用以下功能找到日期差异:
-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 { // Manage Date Formation same for both dates NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy"]; NSDate *startDate = [formatter dateFromString:date1]; NSDate *endDate = [formatter dateFromString:date2]; unsigned flags = NSDayCalendarUnit; NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0]; int dayDiff = [difference day]; return dayDiff; }
来自Abizern的ans.找到更多NSDateComponent here.的信息