How do you generate a random date in objective-c?

Here framework does a good job at generating random date. But in Swift: https://github.com/thellimist/SwiftRandom/blob/master/SwiftRandom/Randoms.swift

public extension NSDate {
    /// SwiftRandom extension
    public static func randomWithinDaysBeforeToday(days: Int) -> NSDate {
        let today = NSDate()

        guard let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) else {
            print("no calendar \"NSCalendarIdentifierGregorian\" found")
            return today
        }

        let r1 = arc4random_uniform(UInt32(days))
        let r2 = arc4random_uniform(UInt32(23))
        let r3 = arc4random_uniform(UInt32(23))
        let r4 = arc4random_uniform(UInt32(23))

        let offsetComponents = NSDateComponents()
        offsetComponents.day = Int(r1) * -1
        offsetComponents.hour = Int(r2)
        offsetComponents.minute = Int(r3)
        offsetComponents.second = Int(r4)

        guard let rndDate1 = gregorian.dateByAddingComponents(offsetComponents, toDate: today, options: []) else {
            print("randoming failed")
            return today
        }
        return rndDate1
    }

    /// SwiftRandom extension
    public static func random() -> NSDate {
        let randomTime = NSTimeInterval(arc4random_uniform(UInt32.max))
        return NSDate(timeIntervalSince1970: randomTime)
    }

}

  1. Generate a random number between 1 and 60

    int r = arc4random_uniform(60) + 1;
    
    // Usage : arc4random_uniform(hi - lo + 1) + lo
    
  2. Get current date

    [NSDate date];
    
  3. Use NSDateComponents to subtract the random number from your days component and generate a new date.


Get a random number and use it as a time interval, then add that to the start date. E.g.

NSTimeInterval timeBetweenDates = [endDate timeIntervalSinceDate:startDate];
NSTimeInterval randomInterval = ((NSTimeInterval)arc4random() / ARC4RANDOM_MAX) * timeBetweenDates;

NSDate *randomDate = [startDate dateByAddingTimeInterval:randomInterval];

This is a Swift 4.x extension that will allow you to specify a period of days, which it will then use to find a random Date before or after the current date.

extension Date {
    static func randomDate(range: Int) -> Date {
        // Get the interval for the current date
        let interval =  Date().timeIntervalSince1970
        // There are 86,400 milliseconds in a day (ignoring leap dates)
        // Multiply the 86,400 milliseconds against the valid range of days
        let intervalRange = Double(86_400 * range)
        // Select a random point within the interval range
        let random = Double(arc4random_uniform(UInt32(intervalRange)) + 1)
        // Since this can either be in the past or future, we shift the range
        // so that the halfway point is the present
        let newInterval = interval + (random - (intervalRange / 2.0))
        // Initialize a date value with our newly created interval
        return Date(timeIntervalSince1970: newInterval)
    }
}

You call it like this:

Date.randomDate(range: 500) // Any date that is +/- 500 days from the current date

Running this 10 times produces:

2019-03-15 01:45:52 +0000
2018-12-20 02:09:51 +0000
2018-06-28 10:28:31 +0000
2018-08-02 08:13:01 +0000
2019-01-25 07:04:18 +0000
2018-08-30 22:37:52 +0000
2018-10-05 19:38:22 +0000
2018-11-30 04:51:18 +0000
2019-03-24 07:27:39 +0000