查找iphone中两个日期之间的总天数 [英] find total number of days between two dates in iphone
本文介绍了查找iphone中两个日期之间的总天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想查找两个日期之间的总天数。
I would like to find total number of days between two dates.
例如。今天是01-01-2011(DD-MM-YYYY),第二个日期是(25-03-2011),我如何找到总天数?
e.g. today is 01-01-2011(DD-MM-YYYY) and second date is (25-03-2011), how would I find the total number of days?
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位代码获得一天的差异。
In your date Format tor u set wrong it`s be dd-MM-yyyy HH:mm:ss . may be that was the problem.. u get wrong date and not get answer i send litte bit code for get day diffrence.
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:
我们可以使用以下函数找到日期差异:
we can find date difference using following function :
-(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;
}
查找更多有关NSDateComponent的信息 here。
from Abizern`s ans. find more infromation for NSDateComponent here.
这篇关于查找iphone中两个日期之间的总天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文