In Ruby, is there a way (a gem, perhaps) to proces

2019-08-15 17:11发布

In particular, to add time (e.g. 11:40 + 00:30 = 12:10) and check whether a time belongs to a range (e.g. (11:00..12:00).include?(11:30)). I understand that I can write a class, but maybe a solution already exists. The built-in Time class is not entirely what I want, because I am not interested in date-related features, which are built-in.

标签: ruby time
2条回答
Summer. ? 凉城
2楼-- · 2019-08-15 17:46

ActiveSupport's Numeric will help you.

You can do:

require 'date'
require 'active_support/all'
DateTime.parse("11:40") + 30.minutes

You will need the ActiveSupport gem in your Gemfile.

As for checking if a time is in a range you can use #cover:

irb(main):001:0> (DateTime.parse("11:40")..DateTime.parse("11:50")).cover?(DateTime.parse("11:45"))
=> true
irb(main):002:0> (DateTime.parse("11:40")..DateTime.parse("11:50")).cover?(DateTime.parse("12:00"))
=> false
查看更多
疯言疯语
3楼-- · 2019-08-15 18:03

You can use strftime to format the time any way you want. If you want only the hour and minutes you can use this:

Time.now.strftime("%H:%M")
 => "08:57"

time.strftime gives you all of these options to format

%a - The abbreviated weekday name (“Sun”)

%A - The full weekday name (“Sunday”)

%b - The abbreviated month name (“Jan”)

%B - The full month name (“January”)

%c - The preferred local date and time representation

%d - Day of the month (01..31)

%H - Hour of the day, 24-hour clock (00..23)

%I - Hour of the day, 12-hour clock (01..12)

%j - Day of the year (001..366)

%m - Month of the year (01..12)

%M - Minute of the hour (00..59)

%p - Meridian indicator (“AM” or “PM”)

%S - Second of the minute (00..60)

%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)

%W - Week number of the current year, starting with the first Monday as the firstday of the first week (00..53)

%w - Day of the week (Sunday is 0, 0..6)

%x - Preferred representation for the date alone, no time

%X - Preferred representation for the time alone, no date

%y - Year without a century (00..99)

%Y - Year with century

%Z - Time zone name

%% - Literal “%” character

Here is a link to the strftime docs

To check if time belongs to a certain range you can use the cover method

2.1.5 :003 > (Time.now..Time.now+10).cover?(Time.now)
 => true

2.1.5 :004 > (Time.now..Time.now+10).cover?(Time.now+20)
 => false
查看更多
登录 后发表回答