我需要设置一个if / else语句,只比较两个NSDates的月份和日期。其中一个日期是使用UIDatePicker选择的,另一个是今天的日期。如果两者的月份和日期相同,则会发生一些事情,如果不是其他事情发生的话。
这就是我目前设置它的方式,但它不起作用(else语句总是触发)。不确定从哪里开始:
.h
@interface ViewController : UIViewController {
UIDatePicker *datePicker;
NSDate *pickedDate;
NSDateFormatter *pickedDateFormat;
NSString *pickedDateString;
NSDate *todaysDate;
NSDateFormatter *todaysDateFormat;
NSString *todaysDateString;
UILabel *label;
}
.m
- (IBAction)buttonToCompareDates:(id)sender {
// Sets date from date picker
pickedDate = [datePicker date];
pickedDateFormat = [[NSDateFormatter alloc] init];
[pickedDateFormat setDateFormat:@"MM/dd"];
pickedDateString = [pickedDateFormat stringFromDate:pickedDate];
// Sets today's date
todaysDate = [NSDate date];
todaysDateFormat = [[NSDateFormatter alloc] init];
[todaysDateFormat setDateFormat:@"MM/dd"];
todaysDateString = [todaysDateFormat stringFromDate:todaysDate];
// if/else statement
if (todaysDateString == pickedDateString) {
label.text = @"The dates match.";
} else {
label.text = @"The dates don't match.";
}
}
我认为这可行,但事实并非如此。我只需要匹配NSDates的月和日部分,因此我尝试将它们格式化为这些部分并比较字符串。问题是,即使日期匹配,我总是得到"The dates don't match."
句子。不知道为什么,可以使用解释和正确的方法来解决这个问题。
答案 0 :(得分:2)
你必须使用
if ([todaysDateString isEqualToString:pickedDateString]) {
而不是
if (todaysDateString == pickedDateString) {
因为你必须比较字符串内容而不是它们的指针。
您还可以使用相同的日期格式化程序优化您的实现:
- (IBAction)buttonToCompareDates:(id)sender {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd"];
// Sets date from date picker
pickedDate = [datePicker date];
pickedDateString = [dateFormatter stringFromDate:pickedDate];
// Sets today's date
todaysDate = [NSDate date];
todaysDateString = [dateFormatter stringFromDate:todaysDate];
// if/else statement
if ([todaysDateString isEqualToString:pickedDateString]) {
label.text = @"The dates match.";
} else {
label.text = @"The dates don't match.";
}
}
答案 1 :(得分:2)
比较字符串可行,但使用NSCalendar可能更有效:
NSDate *date1, *date2;
NSDateComponents* components1 = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date1];
NSDateComponents* components2 = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date2];
if (components1.month == components2.month && components1.day == components2.day) {
// same month and day
} else {
// not same month and day
}
答案 2 :(得分:0)
现在,从iOS 8+开始,就像:
NSDateComponents* components1 = [[NSCalendar currentCalendar] components:NSCalendarUnitMonth|NSCalendarUnitDay fromDate:dateArticle];
NSDateComponents* components2 = [[NSCalendar currentCalendar] components:NSCalendarUnitMonth|NSCalendarUnitDay fromDate:frDateNow];
if (components1.month == components2.month && components1.day == components2.day) {
// same month and day
} else {
// not same month and day
}