Tyilo
Tyilo

Reputation: 30102

Negative NSTimeInterval in NSDate's dateWithTimeIntervalSinceNow:

From the iOS docs:

seconds
The number of seconds from the current date and time for the new date. Use a negative value to specify a date before the current date.

However this code gives dates in 2148:

#import <Foundation/Foundation.h>
#import <stdlib.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        for(int i = 0; i < 30; i++) {
            NSDate* date = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval)-((u_int32_t)i * 12 * 60 * 60 + arc4random_uniform(8 * 60 * 60))];
            NSLog(@"%@", date);
        }

    }
    return 0;
}

It should generates semi-random date and times from the near past.

Upvotes: 2

Views: 2766

Answers (1)

Tyilo
Tyilo

Reputation: 30102

As Hot Licks said, it was due to casting to NSTimeInterval after making the number negative instead of first negating the number and afterwards casting it.

The fixed version of the line will look like this:

NSDate* date = [NSDate dateWithTimeIntervalSinceNow:-(NSTimeInterval)((u_int32_t)i * 12 * 60 * 60 + arc4random_uniform(8 * 60 * 60))];

Upvotes: 7

Related Questions