Skip to content

Instantly share code, notes, and snippets.

@edmund-h
Last active August 13, 2021 17:47
Show Gist options
  • Save edmund-h/2638e87bdcc26e3ce9fffc0aede4bdad to your computer and use it in GitHub Desktop.
Save edmund-h/2638e87bdcc26e3ce9fffc0aede4bdad to your computer and use it in GitHub Desktop.
A function to create a random date in Swift 3
// credit to @eirnym, adapted this from their OBJC code: https://gist.github.com/eirnym/c9526a045556e4d8464b41a367843e3c
// generates a random date and time in the past, limited by daysBack (a number of days before today)
// also generates a random time to go with that date.
// original request: http://stackoverflow.com/questions/10092468/how-do-you-generate-a-random-date-in-objective-c
func generateRandomDate(daysBack: Int)-> Date?{
let day = arc4random_uniform(UInt32(daysBack))+1
let hour = arc4random_uniform(23)
let minute = arc4random_uniform(59)
let today = Date(timeIntervalSinceNow: 0)
let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
var offsetComponents = DateComponents()
offsetComponents.day = -1 * Int(day - 1)
offsetComponents.hour = -1 * Int(hour)
offsetComponents.minute = -1 * Int(minute)
let randomDate = gregorian?.date(byAdding: offsetComponents, to: today, options: .init(rawValue: 0) )
return randomDate
}
@CommanderPho
Copy link

CommanderPho commented May 23, 2018

This seems to be the reverse of what is described in the comments:
It actually gives a random date/time in the future, still limited by the argument number of days.

I believe it could be simply corrected: by either changing line 17 to
offsetComponents.day = -Int(day - 1) // Adding the minus sign
or by changing the documentation to reflect that it actually gives days in the future, and changing the argument name to daysAhead

@edmund-h
Copy link
Author

This seems to be the reverse of what is described in the comments:
It actually gives a random date/time in the future, still limited by the argument number of days.

I believe it could be simply corrected: by either changing line 17 to
offsetComponents.day = -Int(day - 1) // Adding the minus sign
or by changing the documentation to reflect that it actually gives days in the future, and changing the argument name to daysAhead

Thanks! Fixed

@johnhenryking
Copy link

johnhenryking commented Jan 20, 2020

To make it truly random, (on line 17) you can change "-1" to:
Bool.random() == true ? 1 : -1

This will allow some dates to be in the future and some to be in the past.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment