0

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
dimakura
  • 7,575
  • 17
  • 36
John
  • 1,273
  • 3
  • 27
  • 61

3 Answers3

1

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.

Aakanksha
  • 956
  • 1
  • 13
  • 26
0

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).

dimakura
  • 7,575
  • 17
  • 36
  • how to get this in the specific time zone "Asia ,pacific " will the Time.now and DateTime.now gives the time in time zone configured in application.rb file? – John Sep 11 '15 at 07:32
  • It should not depend on specific time zone. It would be helpful if you can state your problem more explicitly. – dimakura Sep 11 '15 at 07:39
0

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.

frankpinto
  • 166
  • 7
  • This wouldn't work as the `strftime` returns the minutes in string and hence if hours is 20, then `hours * 60` would just return something like `202020202020202020202020...` which is clearly not correct. – Aakanksha May 27 '17 at 05:11
  • Nice catch @Aakanksha, fixed – frankpinto Jun 05 '17 at 20:39