【问题标题】:How to compare two strings in objective-c [duplicate]如何在objective-c中比较两个字符串[重复]
【发布时间】:2011-06-11 22:27:27
【问题描述】:

可能的重复:
Comparing dates
How to compare two dates in Objective-C

例如,我想比较日期格式为“11-06-2011”和“12-06-2011”的 2 个字符串。 我想看看第二个日期是否大于第一个日期 你能帮帮我吗?


我试过这个代码

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MM-YYYY"];
    NSDate *date1 = [dateFormat dateFromString:deparatureDateField.text];
    NSDate *date2 = [dateFormat dateFromString:comebackDateField.text];
    [dateFormat release];
    NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2];
    if(timeInterval >= 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Attention" message:@"come back date should be greater" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
        [alert show];
    }

但我总是有警报,NSTimeInterval timeInterval 总是为 NULL

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    要确定一个日期是否大于另一个日期,您必须这样做:

    NSString *string1 = @"11-06-2011";
    NSString *string2 = @"12-06-2011";
    
    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MM-yyyy"];
    NSDate *date1 = [dateFormat dateFromString:string1];
    NSDate *date2 = [dateFormat dateFromString:string2];
    [dateFormat release];
    
    NSComparisonResult comparisonResult = [date1 compare:date2];
    
    /*
    NSComparisonResult can be either of these values:
     - NSOrderedAscending (-1) //if date1 < date2
     - NSOrderedSame (0)       //if date1 = date2
     - NSOrderedDescending (1) //if date1 > date2
    */
    

    或者(到compare:)您可以使用timeIntervalSinceDate: 来获取实际时差:

    NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2];
    //timeInterval will be
    // - nagative if ascending,
    // - zero if same,
    // - positive if descending
    

    【讨论】:

    • @Regexident @murat thakyou 但我认为我的问题不清楚。我不想看是否相等,我想看看第二个日期是否大于第一个日期
    • @user794317:更新了我的答案。见第二个 sn-p。
    • @Regexident 非常感谢你,但我总是遇到麻烦,我更新了我的问题
    • @user794317:我的错。我弄错了日期格式字符串。 YYYY 必须小写,dd-MM-yyyy,即。
    • @user794317:我总是将案例与这些日期格式混为一谈。 :P 顺便说一句,点击投票下方的绿色复选标记,您可以接受答案并将问题标记为已解决。
    【解决方案2】:

    其实这取决于你比较之后会做什么。如果要将日期信息保留为字符串并比较字符串是

       [@"11-06-2011" isEqualToString: @"12-06-2011"]
    

    对你来说足够了

    【讨论】:

      【解决方案3】:

      查看 NSDates timeIntervalSinceNow,您可以比较两个日期的时间间隔,看看哪一个是最近的等等。

      NSTimeInterval *interval = [someDate timeIntervalSinceNow];
      

      【讨论】:

      • 如果有[date1 timeIntervalSinceDate:date2] ;)
      猜你喜欢
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多