开发者

How i campare two dates in Iphone?

I want to set date and time two days after my current date and time.How i set it using NSDate and dateformatter. I want compare date after two days, it was perviously set or not.

I write code now for it, 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]];
[dat开发者_如何学PythoneComps 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];

How i compare it with current time and date? Thanks


Look in NSDate.h and read Apple's docs for the -compare function on NSDates.

You can do for example:

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
}


I think you need NSDateComponents. You can use this class to get year, month, day, and other attributes about date and time.


NSDate * now = [NSDate date];
NSDate * twoDaysFromNow = [now dateByAddingTimeInterval:(2 * 24* 60 * 60)];

You can compare with NSDate's -earlierDate: or -laterDate: methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜