【问题标题】:Compare two strings like date比较两个字符串,如日期
【发布时间】:2012-10-03 20:15:37
【问题描述】:

需要比较两个 NSDate 类型的变量。 一个是当前日期,另一个是用户选择的日期。

用户选择日期:

UIDatePicker *datePicker;   // declared in h file

-(void)dateChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-yyy"];
dateLabel.text = [NSString stringWithFormat:@"%@", [df stringFromDate:datePicker.date]];

userDebtInfo.duration = dateLabel.text;}

验证方法:

-(IBAction) validation:(id)sender{
NSDate *today = [NSDate date];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *dateString = [dateFormat stringFromDate:today];

[dateFormat release];

 if ((userDebtInfo.debt_code == userTmp.debt_code) && ([userDebtInfo.duration compare:dateString]== NSOrderedDescending)))
            [bl updateUserMoneyValidation:userDebtInfo];  
 else
      [bl saveUserMoneyValidation:userDebtInfo];}

我已经测试并正在比较两个字符串。有人可以帮我就这种情况提供一些建议吗? 我想比较选择的日期是否在当前日期之后插入或更新数据库。

  谢谢!

【问题讨论】:

  • 为什么人们总是写[NSString stringWithFormat:@"%@", otherString][NSString stringWithString:otherString]和类似的多余的、浪费处理器时间的调用?
  • @H2CO3 好电话,伙计。我刚刚发现我自己有几个这样的 xD

标签: iphone ios nsdate nsdateformatter nsdatepicker


【解决方案1】:

你可以使用 NSDate 比较功能

if([firstDate compare:secondUpdate] == NSOrderedAscending){
       //This will return YES if secondUpdate is the recent date between the two dates
}

NSOrderedAscending 是 NSComparisonResult 的常量 以下是您可以比较的其他常量:

enum {
 NSOrderedAscending = -1,
 NSOrderedSame,
 NSOrderedDescending
};
typedef NSInteger NSComparisonResult;

【讨论】:

    【解决方案2】:

    如果您已经有两个 NSDate 类型的对象,您可以使用其中一种 NSDate 比较方法。例如[NSDate compare:],它返回一个NSComparisonResult(这与[NSString compare:] 返回的枚举相同)。

    【讨论】:

      猜你喜欢
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 2013-06-24
      • 2014-04-21
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      相关资源
      最近更新 更多