0

我想知道如何减去两个具有日期选择器的文本字段。并将结果显示为标签。例如:(25.05.2013) – (17.05.2013) = 1零1

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;
4

2 回答 2

0

首先你需要转换NSStringNSDateusing NSDateFormatter

然后找到两个日期之间的间隔,这将为您提供秒数,然后您可以根据需要将其转换为分钟、日期。

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];

*代码未编译 - 检查。

于 2013-05-26T03:11:05.890 回答
0

尝试使用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];

您可以有许多组件用于日期差异划分。

如果有任何疑问,请随意询问(:

于 2013-05-28T12:20:06.317 回答