Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
@nbasham

This comment has been minimized.

Copy link
Owner Author

@nbasham nbasham commented Apr 21, 2019

Example usage using Date

        let date1 = Date.parse("2018-01-01")
        let date2 = Date.parse("2019-01-01")
        print(Date.randomBetween(start: date1, end: date2)) // 2018-08-10 01:28:42 +0000

Example usage using String

        let date1 = "2018-01-01"
        let date2 = "2019-01-01"
        print(Date.randomBetween(start: date1, end: date2)) //    2018-03-24

Example usage using String and formatting

        let date1 = "1/1/2018"
        let date2 = "1/1/2019"
        print(Date.randomBetween(start: date1, end: date2, format: "d/M/YYYY")) //    10/7/2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment