How can I calculate the difference between two dates?

后端 未结 9 1393
渐次进展
渐次进展 2020-11-28 02:27

How can I calculate the days between 1 Jan 2010 and (for example) 3 Feb 2010?

9条回答
  •  余生分开走
    2020-11-28 03:10

    NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
    NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];
    
    NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
    
    int numberOfDays = secondsBetween / 86400;
    
    NSLog(@"There are %d days in between the two dates.", numberOfDays);
    

    EDIT:

    Remember, NSDate objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter, the NSDateFormatter converts the time from the configured timezone. Therefore, the number of seconds between two NSDate objects will always be time-zone-agnostic.

    Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.

提交回复
热议问题