Comparing time and date in objective C

后端 未结 2 1174
暗喜
暗喜 2021-01-15 08:48

How do I compare in objective C to see if a certain time and date period overlaps another that is already in a plist for example?

This is most commonly used in booki

相关标签:
2条回答
  • 2021-01-15 09:01

    Try this to Compare ..

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
                [dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss aa"];
    
    
    NSDate *dateOne=[dateFormat dateFromString:@"01/09/2011 11:12:10 AM" ];
            NSDate *dateTwo = [NSDate date];
    
            switch ([dateOne compare:dateTwo]){
                case NSOrderedAscending:
                    //NSLog(@"NSOrderedAscending");
                    break;
                case NSOrderedSame:
                    //NSLog(@"NSOrderedSame");
                 {
    break;
                case NSOrderedDescending:
                    //NSLog(@"NSOrderedDescending");
                    break;
            }
    
    [dateFormat release];
    
    0 讨论(0)
  • 2021-01-15 09:02

    Assuming you have the date stored as a NSDate, just use this:

     [myDate timeIntervalSinceNow];
    

    That returns a NSTimeInterval which is just a float representing the time interval in seconds. If it is negative that means that the time that you are comparing is previous.

    If your date is stored in the plist as a NSString you have to convert it to a NSDate first, use a NSDateFormatter for that.

    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //Change this to your date format
    NSDate * date = [formatter dateFromString:yourString];
    [formatter release];
    
    0 讨论(0)
提交回复
热议问题