Random Time in between two times (a range) iOS SDK - ios

I am trying to create a random time for a notification to occur that is between two times, a range...
I would like iOS to create a time between say 09:30AM and 11:30AM.
I was thinking of using the random number generator for the hours and another one for the minutes and then do some checks to make sure it is between 09:30AM and 11:30 AM but thought there might be an easier way to do it with out getting too involved. any help would be greatly appreciated.

Get an NSTimeInterval for the period between the two dates; get a single random number in that range; get a new date by offset from the first.
/*! Returns a random date in the range [start, end)
#param start The lower bound for random dates; returned dates will be equal to
or after the start date.
#param end The upper bound for random dates; dates will be before the end date.
#returns A random date.
*/
- (NSDate *)randomDateBetweenStart:(NSDate *)start end:(NSDate *)end
{
NSTimeInterval window = [end timeIntervalSinceDate:start];
NSTimeInterval randomOffset = drand48() * window;
return [start dateByAddingTimeInterval:randomOffset];
}
Addendum, a year-and-a-half later: an edit has pointed out that drand48 both has a well-defined sequence (including first value from program launch) and isn't a particularly advanced random number generator. I recommend srand48 or seed48 at program launch if the former is a problem, and something like ((double)arc4random() / UINT32_MAX) in place of drand48 if you want to eliminate both problems — although that reduces the number of output values you can hit from 2^48 to 2^32, it should still get you sub-second decisions within any reasonable time interval.

Related

Will multiple Date() value(timestamp) be equal while initializing in same method and same thread?

I'm curious to know that initializing Date() objects in same method and same thread will be equal to orderedSame. I tried it with unit Test Case but It given various results as attached screenshots.
Test case failed at Assert#2:
Test case failed at Assert#4:
Test case Success:
I think, the time components of Date() will be changing based on the code execution time from date1 to date5.
So can we say that the Date() object created at line #2 will be different from the one created in line #1?
You cannot assume anything. Date()
Creates a date value initialized to the current date and time.
Two consecutive Date() calls can return the same value because
the internal clock has a limited resolution,
the date is stored as a TimeInterval aka Double, which has a limited
precision.
Usually, the values would be non-decreasing, but even that need not be the case
because the user can change the time settings of the device.
Each time you call Date() the system fetches the time from it's realtime clock. If any measurable time has passed between that call and the previous call, the dates will be different. Date objects use a Double count of seconds internally, which has a precision of ≈15 decimal digits, so they are able to measure tiny, tiny spans of time (less than a picosecond.) I don't know the precision of the realtime clock on iOS, but it's will likely be in nanoseconds.
Try running this code in release mode on your target device:
let arraySize = 1000
var array = [Date]()
var differences = 0
array.reserveCapacity(arraySize)
for _ in 1...arraySize {
array.append(Date())
}
for index in 0 ..< arraySize-1 {
if array[index] != array[index+1] {
differences += 1
let difference = array[index+1].timeIntervalSinceReferenceDate -
array[index].timeIntervalSinceReferenceDate
print("Dates at index \(index) are different! by \(difference)")
}
}
if differences == 0 {
print("All dates are equal")
} else {
print("\(differences) dates were different out of \(arraySize)")
}
I ran it as a command-line tool on my Mac and found that I always got at least a couple of dates that were different. (Macs run a lot faster than iOS devices)
Modern iOS devices are multi-core, interrupt driven devices, so the results will vary from run to run.
Absolutely each object is different from another object because every individual object has its different address.
When You create date by Date() system requested new timestamp. Depending on whole system load You can get small delay. Date objects are sensetive to miliseconds, so You have no guarantee that objects will be created in same milisecond. To check this You can check timeIntervalSince1970 of each date (this method will return Unix timestamp.

MVC Getting number of days between calendar start date and end date

I have 2 calendars, one for the user to select the start date and the other for the end date. I want to get the value of the difference between the two dates to display the number of days.
decimal period = Convert.ToDecimal((currentApplication.StartDate.Value - currentApplication.EndDate.Value).TotalDays);
currentApplication.NoOfDays = period;
It does work but number of days isn't accurate.
22/12 to 22/12 is displayed as 1.00
22/12 to 23/12 is displayed as -1.00
22/12 to 24/12 is displayed as -1.00
I thought using .TotalDays would be right but the values aren't accurate. Did I use it wrongly or is .TotalDays not meant to be used this way?
If number of days isn't accurate when using .TotalDays then you can use Timespan to get you number of days.
TimeSpan tSpan = (currentApplication.EndDate.Value).Subtract(currentApplication.StartDate.Value);
currentApplication.NoOfDays = tSpan.Days;
Note: Please make sure currentApplication.StartDate.Value and currentApplication.EndDate.Value are DateTime.
Try;
decimal period = (currentApplication.startDate.Date - currentApplication.endDate.Date).TotalDays
I'm assuming that startDate and endDate are of type Nullable<DateTime>.
You should check HasValue for existence of Value first. This code should work for you.
if(currentApplication.StartDate.HasValue && currentApplication.EndDate.HasValue)
{
currentApplication.NoOfDays = (currentApplication.EndDate.Value.Date - currentApplication.StartDate.Value.Date).Days;
}

SQLITE strange timestamp and IOS

I'm trying to display a simple tableview in IOS with data from Sqlite. My database date is stored as a timestamp. I thought was an unix timestamps but if i try to use dateWithTimeIntervalSince1970 i've really strange result.
Examples of date rows stored:
1352208510267
1352208512266
1352208514266
1352208516266
1352208530266
1352208532265
Use a query like this
SELECT datetime(timestamp, 'unixepoch') from YOURTABLENAME
WHERE id = someId;
This should convert it to some readable value.
Have a look here
I found the answer here. I compared the results with the previous answers:
SELECT strftime('%Y-%m-%d %H:%M:%S', datetime(ZDATE+978307200, 'unixepoch', 'localtime')), datetime(ZDATE, 'unixepoch', 'localtime') FROM ZTABLE
The query with the adjustment for Apple's epoch (Jan 1 2001) gives me the correct date:
"2015-09-29 20:50:51", "1984-09-28 20:50:51"
"2015-09-29 21:03:10", "1984-09-28 21:03:10"
"2015-09-29 21:25:30", "1984-09-28 21:25:30"
Unix timestamps are defined as the number of seconds since Jan 1 1970.
Just now, this would be about 1365525702.
Your values are one thousand times larger, i.e., they are measured in milliseconds.
Decide whether you actually need the millisecond precision, and then add * 1000 or / 1000 at the appropriate places.

RoR Time into Seconds Question

Let's say I want to find out the difference in seconds between two times. One of the times is the created_at attribute of the element, and the other time is a random fixed time in the past. How would I find the difference between the two, and transform it into seconds?
Lucky for you the - operator in ruby returns you an float which is the difference in seconds.
difference_in_seconds = x.created_at - random_time_in_past
It should be as simple as:
time = Time.now
offset = time - record.created_at
offset will now be a Float which is the difference in seconds between the two compared Time objects.

Calculating how many 'Midnights' is one date past another in PHP?

I have a start/end times for a calculation I'm trying to do and am having a problem seeing if the end time is before 12AM the day after the start time. Also, I need to calculate how many days past the start time it is.
What I have: Start Date, End Date
What I need:
- How many 'Midnights' is the End Date past the Start Date?
Has anyone done anything like this?
This uses PHP 5.3, if you have an earlier version you may need to use unix timestamps to figure out the difference. The number of midnights should be the number of days difference assuming both start and end times have the same time. So setting both to be midnight of their current day setTime(0,0), should make the calculation correct.
Using the DateTime objects.
$start = new DateTime('2011-03-07 12:23:45');
$end = new DateTime('2011-03-08 1:23:45');
$start->setTime(0,0);
$end->setTime(0,0);
$midnights = $start->diff($end)->days;
Without using the setTime() calls, this would result in 0, because there is less than 24 hours between start and end. With the setTime() this results in 1 because now the difference is exactly 24 hours.
The diff() function was introduced in 5.3 along with the DateInterval class. In 5.2 you can still use the DateTime class but will have to work out the total days using the Unix timestamp.
$midnights = ($end->format('U') - $start->format('U')) / 86400
You can wrap that in an abs() function to the order of start/end does not matter.
Note: These functions may need to be tested for cases that involve DST.
A comment in the php date documentation uses round after dividing by 86400 (number of seconds in a day), to counter any issues that could be involved with DST.
An alternative approach with DateTimes would be to create them in the UTC.
$utcTimezone = new DateTimeZone('UTC');
$start = new DateTime('2011-03-07 12:23:45', $utcTimezone);
$end = new DateTime('2011-03-08 1:23:45', $utcTimezone);

Resources