Comparing certain components of NSDate?

前端 未结 4 451
青春惊慌失措
青春惊慌失措 2021-01-05 21:35

How would I compare only the year-month-day components of 2 NSDates?

4条回答
  •  被撕碎了的回忆
    2021-01-05 22:23

    Check out this topic NSDate get year/month/day

    Once you pull out the day/month/year, you can compare them as integers.

    If you don't like that method

    Instead, you could try this..

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy"];
    int year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    
    [dateFormatter setDateFormat:@"MM"];
    int month = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    
    [dateFormatter setDateFormat:@"dd"];
    int day = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    
    • And another way...

      NSDateComponents *dateComp = [calendar components:unitFlags fromDate:date];
      
      NSInteger year = [dateComp year];
      
      NSInteger month = [dateComp month];
      
      NSInteger day = [dateComp day];
      

提交回复
热议问题