简体   繁体   English

比较两个字符串,如日期

[英]Compare two strings like date

Need to compare two variables of type NSDate. 需要比较两个NSDate类型的变量。 One is the current date and the other is user selected date. 一个是当前日期,另一个是用户选择的日期。

The user selects the date : 用户选择日期:

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

Validation Method : 验证方法:

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

I have tested and is comparing two strings. 我已经测试过并且正在比较两个字符串。 Can someone help me with some advice about this condition, please? 有人可以帮我提供一些有关这种情况的建议吗? I want to compare if the selected date is after the current date to do insert or update the database. 我想比较所选日期是否在当前日期之后,以进行插入或更新数据库。

Thank you! 谢谢!

You could use NSDate compare function 您可以使用NSDate 比较功能

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

NSOrderedAscending is a constant of NSComparisonResult Here are the other constants you could compare to: NSOrderedAscending是NSComparisonResult的常量,以下是您可以比较的其他常量:

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

If you already have two objects of type NSDate, you could use one of the NSDate comparison methods. 如果您已经有两个NSDate类型的对象,则可以使用NSDate比较方法之一。 For instance [NSDate compare:] which returns a NSComparisonResult (this is the same enum as returned by [NSString compare:] ). 例如,返回一个NSComparisonResult [NSDate compare:] (这与[NSString compare:]返回的枚举相同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM