从文本字段比较日期

时间:2016-07-13 10:07:37

标签: ios objective-c nsdate nsdateformatter

我已在textFields中实施了两个ViewController发件人和收件人。当用户选择textField时,他可以从日历中选择日期。所选日期存储在TextField as中 YYYY-MM-dd格式。

我已经在ViewController中实施了一个计算按钮。当两个TextField被填充时,我需要做一些工作。

当两个textField填充且来自TextField更高时,我想在发件人TextField日期大于TextField时显示提醒。< / p>

我如何比较它??

4 个答案:

答案 0 :(得分:1)

完美的解决方案

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString *textFieldDateString1 = @"2016-07-14";
NSString *textFieldDateString2 = @"2016-07-15";

NSDate *date1 = [dateFormatter dateFromString:textFieldDateString1];
NSDate *date2 = [dateFormatter dateFromString:textFieldDateString2];

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
}

印刷结果

date1 is earlier than date2

Date Comparision

Compare Two dates

答案 1 :(得分:0)

我认为您正在寻找此功能..

using Plots; gr()
data = [1,2,3]
labels = ["one","two","three"]

bar(data, legend=false)

我希望这会对你有帮助..

答案 2 :(得分:0)

   NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat: @"yyyy-MM-dd"];
    NSDate * dt1 ;
    NSDate * dt2 ;
    dt1 = [df dateFromString: txt1.text];
    dt2 = [df dateFromString: txt2.text];
    NSComparisonResult result = [dt1 compare: dt2];
    switch (result) {
        case NSOrderedAscending:
            NSLog(@"%@ is greater than %@", dt2, dt1);
            break;
        case NSOrderedDescending:
            NSLog(@"%@ is less %@", dt2, dt1);
            break;
        case NSOrderedSame:
            NSLog(@"%@ is equal to %@", dt2, dt1);
            break;
        default:
            NSLog(@"erorr dates %@, %@", dt2, dt1);
            break;
    }

希望这会对你有帮助....

答案 3 :(得分:0)

首先,您必须将此两个文本字段字符串日期转换为NSDate对象,并使用compare:日期方法来比较日期。

NSString *dateString1 = @"2016-05-31"; //First text field value
NSString *dateString2 = @"2016-05-31"; //Second text field value
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSDate *date1=[dateFormatter dateFromString:dateString1];
NSDate *date2=[dateFormatter dateFromString:dateString2];

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
}