John
John

Reputation: 1323

how to get time in totally in minutes in rails?

I am using DateTime.now and Time.now methods. And I store it in some variables. Now I want this time in minutes. Meaning, instead of hours and minutes I want to get time in minutes only.

2.2.2 :014 > datetime = DateTime.now
 => Fri, 11 Sep 2015 12:13:00 +0530 
2.2.2 :015 > time = Time.now
 => 2015-09-11 12:13:06 +0530 
2.2.2 :016 > 

Now i want to calculate this time entirely in minutes. is there any method like to_minutes like below?

datetime_in_min = datetime.to_minutes
time_in_min = time.to_minutes

Upvotes: 0

Views: 3929

Answers (3)

frankpinto
frankpinto

Reputation: 166

The strftime method can get you any piece of the time you want. The time in minutes (I'm assuming relative to the beginning of the day) you need to do some math:

hours = datetime.strftime('%k').to_i
hours_in_minutes = hours * 60
minutes = datetime.strftime('%M').to_i
minutes_since_start_of_day = hours_in_minutes + minutes

Same thing works for time.

Upvotes: 0

Aakanksha
Aakanksha

Reputation: 976

This must have already been done by now but just for anyone who's still looking for an answer, try doing something like below

lets assume the we wish to fetch the minutes and the hours from something like

s = Sat, 27 May 2017 02:30:00 UTC +00:00 (date time)

then,

hours = s.strftime("%H")
minutes = s.strftime("%M")
total_minutes((hours.to_i * 60) + minutes)

hence you'll get something like 150

Hope this helps.

Upvotes: 1

dimakura
dimakura

Reputation: 7655

You can use the following method from Time:

Time.now.to_i

to get number of seconds since the Epoch (January 1, 1970 00:00 UTC).

Upvotes: 0

Related Questions