Subtract N Hours from a Datetime in Ruby

Subtract n hours from a DateTime in Ruby

You could do this.

adjusted_datetime = (datetime_from_form.to_time - n.hours).to_datetime

How do you subtract from a datetime?

Rails usually uses Time, not DateTime. Why don't you do Time.now - self.created_at? Then you can convert from seconds to hours by dividing by 3600.

subtract N minutes from rails datetime object

@event.start_at - some_count.minutes will always work within Rails. There's also seconds, hours, days, weeks, months, and years.

How to subtract n months from a DateTime in Ruby?

Since DateTime is a subclass of Date, you can use << or prev_month:

require 'date'

d = DateTime.now #=> #<DateTime: 2018-02-20T15:39:44+01:00 ...>
d << 4 #=> #<DateTime: 2017-10-20T15:39:44+01:00 ...>
d.prev_month(4) #=> #<DateTime: 2017-10-20T15:39:44+01:00 ...>

Note that DateTime doesn't account for daylight savings time.

Ruby Date Subtraction (e.g. 90 days Ago)


require 'date'
now = Date.today
ninety_days_ago = (now - 90)

Running this thru the IRB console I get:

>>require 'date'
now = Date.today
ninety_days_ago = (now - 90)

require 'date'
=> false
now = Date.today
=> #<Date: 2011-03-02 (4911245/2,0,2299161)>
ninety_days_ago = (now - 90)
=> #<Date: 2010-12-02 (4911065/2,0,2299161)>


If you need the time you could just say now = DateTime.now

Subtracting dates in ruby or rails

Date and Time are not the same class so you can't just subtract one from the other.

Try using DateTime instead or coercing time into a date using to_date.

due_date = DateTime.parse '2020-07-18 00:00:00 -0700'
today_date = DateTime.current
(due_date - today_date).to_i

Also be careful using Time.now because it's not time zone aware (https://thoughtbot.com/blog/its-about-time-zones)

Subtracting unit of minutes from Rails datetime value


Time is more complex than you think

Outputting the number of minutes might seem like a pretty simple task but there are several factors you are not weighing in:

  • what happens when game_start is in the past?
  • what happens when game_start is several days into the future/past?

Rails provides some pretty nifty date helpers such as distance_of_time_in_words_to_now which helps with outputting time diffs in a human friendly way:

[1] pry(main)> include ActionView::Helpers::DateHelper
=> Object
[2] pry(main)> distance_of_time_in_words_to_now(50.minutes.from_now)
=> "about 1 hour"
[3] pry(main)> distance_of_time_in_words_to_now(5.minutes.from_now)
=> "5 minutes"

Time and caching

Dealing with user timezones or distance_of_time_in_words can be very problematic from a caching standpoint since it needs to be recalculated on every request.

A better alternative could be to output the time as a timestamp and let the client figure out the diff.

<%= content_tag :time, quiz.game_start, 
class: 'time-diff',
datetime: quiz.game_start.utc.iso8601
%>

This is an example using jQuery and moment.js to format the time. You can do it with vanilla JS but its so lengthy that its a question on its own.





// recursive function that runs once on startup and then every minute

(function updateTimeDiff( interval ){

interval = interval || 60000; // default polling to 1 minute



$(".time_diff").each(function(){

var $el = $(this);

var m = moment($el.attr('datetime') );



$el.text( m.fromNow() );

// this is a unformated diff in minutes

console.log( m.diff(moment(), 'minutes', true) );

});


setTimeout(updateTimeDiff, interval);

})();
<!-- this is just to power the snippet. -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment-with-locales.min.js"></script>

<time class="time_diff" datetime="2016-02-17T15:26:12-04:00">2016-02-17T15:26:12-04:00</time>

How to find the difference between two time in ruby?

If you want it in seconds, you can just convert both to time stamps, and then subtract

time_difference_in_sec = (DateTime.now.to_time.to_i - @given_time.to_time.to_i).abs

Else you wind up dealing with rational numbers, and the like as seen in the other answers..



Related Topics



Leave a reply



Submit