Skip to content

Instantly share code, notes, and snippets.

@nbasham
Last active January 21, 2024 14:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nbasham/c219d8c8c773d2c146c526dfccb4353b to your computer and use it in GitHub Desktop.
Save nbasham/c219d8c8c773d2c146c526dfccb4353b to your computer and use it in GitHub Desktop.
Get a random date between two values. Swift 4.2+ uses Random(in:).
import Foundation
extension Date {
static func randomBetween(start: String, end: String, format: String = "yyyy-MM-dd") -> String {
let date1 = Date.parse(start, format: format)
let date2 = Date.parse(end, format: format)
return Date.randomBetween(start: date1, end: date2).dateString(format)
}
static func randomBetween(start: Date, end: Date) -> Date {
var date1 = start
var date2 = end
if date2 < date1 {
let temp = date1
date1 = date2
date2 = temp
}
let span = TimeInterval.random(in: date1.timeIntervalSinceNow...date2.timeIntervalSinceNow)
return Date(timeIntervalSinceNow: span)
}
func dateString(_ format: String = "yyyy-MM-dd") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
static func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.default
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: string)!
return date
}
}
@its-all-waves
Copy link

its-all-waves commented Nov 7, 2022

@nbasham, that is so nice to hear! It's awfully rare to find encouraging words in these places (here and StackExchange, namely). Thank you for taking the time to say that! You truly made my day!

Unfortunately, I can't take credit for the min/max bit, as that was @BrightScreenTV's idea.

I hear you about respecting the user's choices. The guard statement is a better / cleaner / more respectful way to accomplish what I was trying to. Thank you for sharing your code and your wisdom, sir!

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