NSDate, comparing two dates 比較 是否是相同的日期

February 7, 2014   ·   0 Comments

- (BOOL)isSameDay:(NSDate*)date1 otherDay:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];

- (BOOL)isSameDayString:(NSString*)date1 otherDay:(NSString*)date2 {
    // powenko 比較 是否是相同的日期
    NSString *currentDateString = date1; //@"8/5/2011 1:38:13 PM";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //Specify only 1 M for month, 1 d for day and 1 h for hour
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
    NSDate *currentDate2 = [dateFormatter dateFromString:date2];
    [dateFormatter release];
    return [self isSameDay:currentDate otherDay:currentDate2];
shareShare on FacebookShare on Google+Share on LinkedInEmail this to someonePrint this pageBuffer this pageDigg thisFlattr the authorShare on RedditPin on PinterestShare on StumbleUponShare on TumblrTweet about this on Twitter


Readers Comments (0)

You must be logged in to post a comment.

PowenKo’s Online Store

iOS Tutorial9



Recent Posts