How can I compare two dates, return a number of days

后端 未结 4 1370
生来不讨喜
生来不讨喜 2020-12-05 13:57

how can I compare two dates return number of days. Ex: Missing X days of the Cup. look my code.

  NSDateFormatter *df = [[NSDateFormatter alloc]init];  
  [d         


        
4条回答
  •  攒了一身酷
    2020-12-05 14:49

    Need to call this method and set 2 dates only which we want to calculate differently.

    -(void) calculateSleepHours:(NSDate *)sleepDate :(NSDate *)wakeStr 
    {
    
       if (sleepDate !=nil && wakeStr!=nil) {`enter code here`
    
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
        [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ssZ"];
        NSDate *date1 = [ApplicationManager getInstance].sleepTime;;
    
        NSDate *date2 = [ApplicationManager getInstance].wakeupTime;
    
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];
    
        NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    
        NSDateComponents *components = [gregorian components:unitFlags
                                                    fromDate:date1
                                                      toDate:date2 options:0];
    
        NSInteger months = [components month];
        NSInteger days = [components day];
        NSInteger hours = [components hour];
        NSInteger minute=[components minute];
        NSInteger second=[components second];
        DLog(@"Month %ld day %ld hour is %ld min %ld sec %ld  ",(long)months,(long)days,(long)hours,(long)minute,(long)second);
    
        sleepHours.text=[NSString stringWithFormat:@"Hour %ld Min %ld Sec %ld",(long)hours,(long)minute,(long)second];
        }
    }
    

提交回复
热议问题