Last active
January 21, 2024 14:57
-
-
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:).
This file contains hidden or 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
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 | |
} | |
} |
@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
@its-all-waves I like your use of min/max it's an improvement. As the caller is responsible for the logic behind the dates passed in I would lean towards respecting their choices. If the dates are equal, perhaps a guard statement could just return that date? Your velocity at picking up the language is impressive. I hope you really enjoy Swift, and that I get to see more of your amazing trajectory.