Last active
August 13, 2021 17:47
-
-
Save edmund-h/2638e87bdcc26e3ce9fffc0aede4bdad to your computer and use it in GitHub Desktop.
A function to create a random date in Swift 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
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
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
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