Objective c 减去具有日期选择器的两个文本字段
我想知道如何减去两个有日期选择器的文本字段。并将结果显示到标签中。 示例:(2013年5月25日)–(2013年5月17日)=1周和1日Objective c 减去具有日期选择器的两个文本字段,objective-c,datepicker,nsdate,nscalendar,subtraction,Objective C,Datepicker,Nsdate,Nscalendar,Subtraction,我想知道如何减去两个有日期选择器的文本字段。并将结果显示到标签中。 示例:(2013年5月25日)–(2013年5月17日)=1周和1日 NSDate *now = [NSDate date]; NSDate *then = self.datepicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSUInteger w, d; w = (howLong / 604800); d = NSString
NSDate *now = [NSDate date];
NSDate *then = self.datepicker.date;
NSTimeInterval howLong = [now timeIntervalSinceDate:then];
NSUInteger w, d;
w = (howLong / 604800);
d =
NSString *str = [NSString stringWithFormat:@" x weeks, y days", w, d];
label1.text = str;
首先,需要使用
NSDateFormatter
将NSString
转换为NSDate
然后找出两个日期之间的间隔,这将给你秒,然后你可以根据需要将其转换为分钟,日期
NSDateFormatter *df=[NSDateFormatter new];
[df setDateFormat:@"dd.MM.yyyy"];
NSDate *date1=[df dateFromString:@"25.05.2013"];
NSDate *date2=[df dateFromString:@"17.05.2013"];
NSInteger interval = (int)[date1 timeIntervalSinceDate: date2];
*代码未编译-已检查。尝试使用
NSDateComponents
:
NSDateFormatter *form = [[NSDateFormatter alloc]init];
[form setDateFormat:@"dd.MM.yyyy"];
NSDate *dateA = [form dateFromString:@"17.05.2013"];
NSDate *dateB = [form dateFromString:@"25.05.2013"];
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:dateA
toDate:dateB
options:0];
strDiffyear = [NSString stringWithFormat:@"%i", components.year];
strDiffmonth = [NSString stringWithFormat:@"%i",components.month];
strDiffDays = [NSString stringWithFormat:@"%i",components.day];
lblDifference.text = [NSString stringWithFormat:@"%@ years %@ months %@ days",strDiffyear,strDiffmonth,strDiffDays];
可以有许多用于日期差划分的组件
如果回答中有任何查询,可以自由提问(:从要显示的最大单位开始计算,例如年,然后继续计算下一个单位,例如月,并计算剩余的单位。提示:从1970年开始将两个日期转换为总秒数。