RoR Time into Seconds Question - ruby-on-rails

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.

Related

Store seconds in the database - Rails

I have a Timekeeper model in my app. It keeps track of started_at time and finished_at time. I want to take the difference between these two datetimes and pull out the seconds and store that value in the database as an integer. Here is what I'm currently working with.
Method:
((timekeeper.started_at - Time.current) * 24 * 60 * 60).to_i
This returns a value that looks like this : -2336036
The two times above are only 12 seconds apart and I get that value. I'm not sure what it is saying.
The takeaway from my question is: How can I store seconds in the database, between two datetimes that looks similar to what I'm doing currently?
If you want to find the difference between the 2 times you just need to do the subtraction as the difference is returned in seconds.
time.started_at - Time.current
if you dont want the fraction of a second
(time.started_at - Time.current).to_i
and the absolute value
((time.started_at - Time.current).to_i).abs
try the above in a rails console

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

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.

joda overlap method for ambiguous hour

I'm trying to find out if there is any overlap between two joda intervals. value of the variables are given below. I'm not sure why the overlap is being returned as 'null'.
final Interval overlap = range.overlap(new Interval(beginDateTime, endDateTime));
beginDateTime = 2013-11-03T00:07:00.000Z
endDateTime = 2013-11-03T00:08:00.000Z
range = 2013-11-03T00:00:00.000-05:00/2013-11-03T23:59:59.999-06:00
Interval created by 'beginDateTime' and 'endDateTime' corresponds to ambiguous hour in America/Chicago time zone. Variable 'range' represents November 3rd in America/Chicago time zone.
I tried to debug into Interval.class, could not find out the reason.
thanks.
Never mind, found the issue.
beginDateTime and endDateTime be 2013-11-03T07:00:00.000Z and 2013-11-03T08:00:00.000Z respectively.
My test data was incorrect as listed in the question (that is not ambiguous hour, it is interval of just 1 minute, I swapped minutes with hour values) :)

What is a good way to record time periods in Rails application, so that I can easily use them for calculations?

I have time periods like:
2 years
1 month
4 days
I would like to add them to existing records in my DB in a way that I could easily use them for calculations? The type of calculations I would need would be [time_period] - (Time.now - [datetime]) in order to see how much of the time period is left.
Since my periods are quite standard, I was thinking to save the time periods as strings "2-years", "1-month", "4-days" etc. and split them on use. For example "4-days" could become something like this:
4.send("days".to_sym)
What do you think about this method? Any better ideas?
Okay i have a better solution.
Here is the Class TimeDuration
five_minutes = TimeDuration.new("5 min")
five_minutes + Time.now
Time.now
# => 2013-09-13 02:50:06 +0200
five_minutes + Time.now
# => 2013-09-13 02:55:13 +0200
It would be best to store them all in a standardized format; like seconds, so that you can easily do calculations without having to first convert things. If you also stored some sort of units field (i.e. years, days, minutes, seconds), you could then easily convert the seconds back to their appropriate units for display - sort of like what you have above.
stored_value_in_minutes = stored_value.seconds / 1.minutes

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