Skip to content

Instantly share code, notes, and snippets.

@StevenMasini
Created April 23, 2020 15:48
Show Gist options
  • Save StevenMasini/af8b8d13241aa7eb33edb9f482b53fc9 to your computer and use it in GitHub Desktop.
Save StevenMasini/af8b8d13241aa7eb33edb9f482b53fc9 to your computer and use it in GitHub Desktop.
Create random Date
import Foundation
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment