首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Ruby中,有没有办法(也许是gem )处理"XX:XX“格式的时间?

在Ruby中,有没有办法(也许是gem )处理"XX:XX“格式的时间?
EN

Stack Overflow用户
提问于 2015-02-11 21:47:57
回答 2查看 198关注 0票数 1

特别是,添加时间(例如11:40 + 00:30 = 12:10)并检查时间是否属于某个范围(例如(11:00..12:00).include?(11:30))。我知道我可以写一个类,但可能已经有了解决方案。内置的Time类并不完全是我想要的,因为我对内置的与日期相关的特性不感兴趣。

EN

回答 2

Stack Overflow用户

发布于 2015-02-11 22:01:21

您可以使用strftime以任何您想要的方式格式化时间。如果你只想要小时和分钟,你可以使用这个:

代码语言:javascript
复制
Time.now.strftime("%H:%M")
 => "08:57"

time.strftime为您提供了所有这些格式化选项

代码语言:javascript
复制
%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方法

代码语言:javascript
复制
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
票数 5
EN

Stack Overflow用户

发布于 2015-02-11 22:05:38

ActiveSupport's Numeric将帮助你。

您可以执行以下操作:

代码语言:javascript
复制
require 'date'
require 'active_support/all'
DateTime.parse("11:40") + 30.minutes

您需要在Gemfile中使用ActiveSupport gem。

至于检查时间是否在某个范围内,可以使用#cover

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28455977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档