Comparing the time of two NSDates, ignoring the date component

后端 未结 3 480
孤独总比滥情好
孤独总比滥情好 2020-12-06 02:03

I want to compare two NSDates with NOW ([NSDate date]).

NSDate *date1 = [NSDate dateWithString:@\"1982-02-12 07:00:00 +0100\"];
NSDate *now   = [NSDate dateW         


        
3条回答
  •  天涯浪人
    2020-12-06 02:20

    unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    NSDateComponents* components = [calendar components:flags fromDate:date1];
    
    NSDate* timeOnly = [calendar dateFromComponents:components];
    

    This will give you a date object where everything but the hours/minutes/seconds have been reset to some common value. Then you can use the standard NSDate compare functions on them.

    For reference, here is the opposite question to yours: Comparing two NSDates and ignoring the time component

提交回复
热议问题