-1

I have an application for iPhone that gives information based on the current date. For example if the date is 10/28/13, it will say Today's weather is.... etc. How can I use an "If-Then" statement to find the current date? Or is there another better way of automatically finding the date and adjusting the display of the application?

I've tried implementing this by using a google calendar API but could't get that to work either.

Thanks a lot! This is my 2nd app ever on iOS so I need a lot of help! Thanks!

EDIT Just in case anyone needs this later on, this is what I got to finally work for me

     NSDateFormatter *df= [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-dd"];

NSDate *date1 = [df dateFromString:@"2013-10-27"];
NSDate *date2 = [df dateFromString:@"2013-10-28"];
NSDate *currentDate = [NSDate date];

[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&currentDate interval:NULL forDate:currentDate];
if ([currentDate isEqualToDate:date1]) {
    crowdLabel.text = [NSString stringWithFormat:@"%@", itsOk];
} else {
    crowdLabel.text = [NSString stringWithFormat:@"Not Working"];
}
4

1 回答 1

1
[NSDate date]

将返回当前日期。然后,您可以通过配置和使用NSDateFormatter.

Apple的Data Formatting Guide是一个很好的参考。


好的,您的代码中有几个错误,让我们检查一下

NSDate *dt1 = [[NSDate alloc] init]; 
NSDate *dt2 = [[NSDate alloc] init]; 

考虑到您在初始化后立即分配这两个变量,alloc/init没用,只需执行

NSDate *date1 = [df dateFromString:@"2013-10-27"]; 
NSDate *date2 = [df dateFromString:@"2013-10-28"]; 

NSDate *currentDate = [[NSDate date] init]; 

是错的。date返回一个已经初始化的对象。调用init它是未定义的行为。做就是了

NSDate *currentDate = [NSDate date];

最后也是最重要的是,您无法比较日期

currentDate == dt1

==比较指针,即您正在比较对象身份而不是对象相等性。如果要检查两个NSDate对象是否代表相同的日期,请使用

[currentDate isEqualToDate:date1]

请注意,这将比较包含的完整日期、时间信息。如果只想查看日期部分,可以参考这个问题:iOS: Compare two NSDate-s without time part

于 2013-10-28T00:21:17.727 回答