特别是,添加时间(例如11:40 + 00:30 = 12:10)并检查时间是否属于某个范围(例如(11:00..12:00).include?(11:30))。我知道我可以写一个类,但可能已经有了解决方案。内置的Time类并不完全是我想要的,因为我对内置的与日期相关的特性不感兴趣。
发布于 2015-02-11 22:01:21
您可以使用strftime以任何您想要的方式格式化时间。如果你只想要小时和分钟,你可以使用这个:
Time.now.strftime("%H:%M")
=> "08:57"time.strftime为您提供了所有这些格式化选项
%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以下是指向strftime文档的链接
要检查时间是否属于某个范围,可以使用cover方法
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发布于 2015-02-11 22:05:38
ActiveSupport's Numeric将帮助你。
您可以执行以下操作:
require 'date'
require 'active_support/all'
DateTime.parse("11:40") + 30.minutes您需要在Gemfile中使用ActiveSupport gem。
至于检查时间是否在某个范围内,可以使用#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"))
=> falsehttps://stackoverflow.com/questions/28455977
复制相似问题