我想在当前日期和时间后两天设置日期和时间。如何使用NSDate和dateformatter设置它。我希望在两天之后比较日期,它是否已经过去了。
我现在为它编写代码, NSCalendar * calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *pickerDate = [self.datePicker date];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:00];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
appDelegate.setTimerByUser = [itemDate retain];
我如何将它与当前时间和日期进行比较? 感谢
答案 0 :(得分:1)
查看NSDate.h并阅读Apple的文档,了解NSDates上的-compare函数。
你可以这样做:
NSDate *now = [NSDate date];
NSDate *future = [now dateByAddingTimeInterval: 2 * 24 * 60 * 60]; // add two days
if ( [now compare: future] == NSOrderedAscending ) {
// now is earlier than future so we will always get here
} else {
// never reached but illustrates how you might use compare
}
答案 1 :(得分:0)
我认为你需要NSDateComponents。您可以使用此类来获取有关日期和时间的年,月,日和其他属性。
答案 2 :(得分:0)
NSDate * now = [NSDate date];
NSDate * twoDaysFromNow = [now dateByAddingTimeInterval:(2 * 24* 60 * 60)];
您可以与NSDate的-earlierDate:
或-laterDate:
方法进行比较。