Как создать случайную дату в objective-c?
Я хотел бы создать случайную дату между двумя датами - например, случайную дату между сегодняшним днем и 60 днями. Как это сделать?
UPDATE
Используя информацию из ответов, я придумал этот метод, который я использую довольно часто:
// Generate a random date sometime between now and n days before day.
// Also, generate a random time to go with the day while we are at it.
- (NSDate *) generateRandomDateWithinDaysBeforeToday:(NSInteger)days
{
int r1 = arc4random_uniform(days);
int r2 = arc4random_uniform(23);
int r3 = arc4random_uniform(59);
NSDate *today = [NSDate new];
NSCalendar *gregorian =
[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [NSDateComponents new];
[offsetComponents setDay:(r1*-1)];
[offsetComponents setHour:r2];
[offsetComponents setMinute:r3];
NSDate *rndDate1 = [gregorian dateByAddingComponents:offsetComponents
toDate:today options:0];
return rndDate1;
}
Ответы
Ответ 1
-
Создайте случайное число между 1 и 60
int r = arc4random_uniform(60) + 1;
// Usage : arc4random_uniform(hi - lo + 1) + lo
-
Получить текущую дату
[NSDate date];
-
Используйте NSDateComponents
, чтобы вычесть случайное число из вашего компонента days
и сгенерировать новую дату.
Ответ 2
Получите случайное число и используйте его как временной интервал, затем добавьте его к дате начала. Например.
NSTimeInterval timeBetweenDates = [endDate timeIntervalSinceDate:startDate];
NSTimeInterval randomInterval = ((NSTimeInterval)arc4random() / ARC4RANDOM_MAX) * timeBetweenDates;
NSDate *randomDate = [startDate dateByAddingTimeInterval:randomInterval];
Ответ 3
Здесь структура отлично работает при создании случайной даты. Но в Свифт:
https://github.com/thellimist/SwiftRandom/blob/master/SwiftRandom/Randoms.swift
public extension NSDate {
/// SwiftRandom extension
public static func randomWithinDaysBeforeToday(days: Int) -> NSDate {
let today = NSDate()
guard let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) else {
print("no calendar \"NSCalendarIdentifierGregorian\" found")
return today
}
let r1 = arc4random_uniform(UInt32(days))
let r2 = arc4random_uniform(UInt32(23))
let r3 = arc4random_uniform(UInt32(23))
let r4 = arc4random_uniform(UInt32(23))
let offsetComponents = NSDateComponents()
offsetComponents.day = Int(r1) * -1
offsetComponents.hour = Int(r2)
offsetComponents.minute = Int(r3)
offsetComponents.second = Int(r4)
guard let rndDate1 = gregorian.dateByAddingComponents(offsetComponents, toDate: today, options: []) else {
print("randoming failed")
return today
}
return rndDate1
}
/// SwiftRandom extension
public static func random() -> NSDate {
let randomTime = NSTimeInterval(arc4random_uniform(UInt32.max))
return NSDate(timeIntervalSince1970: randomTime)
}
}
Ответ 4
Это расширение Swift 4.x, которое позволит вам указать период дней, который затем будет использоваться для поиска случайного Date
до или после текущей даты.
extension Date {
static func randomDate(range: Int) -> Date {
// Get the interval for the current date
let interval = Date().timeIntervalSince1970
// There are 86,400 milliseconds in a day (ignoring leap dates)
// Multiply the 86,400 milliseconds against the valid range of days
let intervalRange = Double(86_400 * range)
// Select a random point within the interval range
let random = Double(arc4random_uniform(UInt32(intervalRange)) + 1)
// Since this can either be in the past or future, we shift the range
// so that the halfway point is the present
let newInterval = interval + (random - (intervalRange / 2.0))
// Initialize a date value with our newly created interval
return Date(timeIntervalSince1970: newInterval)
}
}
Вы называете это так:
Date.randomDate(range: 500) // Any date that is +/- 500 days from the current date
Выполнение этого 10 раз приводит к:
2019-03-15 01:45:52 +0000
2018-12-20 02:09:51 +0000
2018-06-28 10:28:31 +0000
2018-08-02 08:13:01 +0000
2019-01-25 07:04:18 +0000
2018-08-30 22:37:52 +0000
2018-10-05 19:38:22 +0000
2018-11-30 04:51:18 +0000
2019-03-24 07:27:39 +0000
Ответ 5
Используйте секунды. Псевдокод:
1 Generate a random integer between 0 and (60 * 60 * 24 * 60)
2 Get the unixtime in seconds for the current time
3 Add your random integer
4 Convert this integer back to a date
Ответ 6
Swift 3.x +
public extension Date {
/// SwiftRandom extension
public static func randomWithinDaysBeforeToday(days: Int) -> Date {
let today = Date()
let gregorian = Calendar(identifier: .gregorian)
let r1 = arc4random_uniform(UInt32(days))
let r2 = arc4random_uniform(UInt32(23))
let r3 = arc4random_uniform(UInt32(23))
let r4 = arc4random_uniform(UInt32(23))
let offsetComponents = NSDateComponents()
offsetComponents.day = Int(r1) * -1
offsetComponents.hour = Int(r2)
offsetComponents.minute = Int(r3)
offsetComponents.second = Int(r4)
let rndDate1 = gregorian.date(byAdding: offsetComponents as DateComponents, to: today)
return rndDate1!
}
/// SwiftRandom extension
public static func random() -> Date {
let randomTime = TimeInterval(arc4random_uniform(UInt32.max))
return Date(timeIntervalSince1970: randomTime)
}
}
<суб > P.S. Esqarrouth answer исправлены для последней версии Swift.Суб >