Ruby中的日期时间比较 [英] Date-time comparison in Ruby
问题描述
我有一次约会,比如说一次航班起飞的"2010-12-20",例如两次,分别是"23:30"和"02:15".
I have one date, let's say '2010-12-20' of a flight departure, and two times, for instance, '23:30' and '02:15'.
问题:我需要获取这两个日期的日期时间(例如,yyyy-MM-dd HH:mm:ss,例如2010-12-17 14:38:32),但我不知道第二次的一天(可以是出发的同一天,也可以是下一天).
The problem: I need to get datetimes (yyyy-MM-dd HH:mm:ss, for example, 2010-12-17 14:38:32) of both of these dates, but I don't know the day of the second time (it can be the same day as departure, or the next one).
我正在寻找Ruby on Rails中的最佳解决方案.在PHP中,会多次使用字符串拆分,但是我相信,像往常一样,Rails拥有一种更为优雅的方法.
I am looking for the best solution in Ruby on Rails. In PHP would just use string splitting multiple times, but I believe, that Rails as usually, has a much more elegant way.
所以,这是我的伪代码,我想将其变成Ruby:
So, here is my pseudo code, which I want to turn into Ruby:
depart_time = '23:30'
arrive_time = '02:15'
depart_date = '2010-12-20'
arrive_date = (arrive.hour < depart.hour and arrive.hour < 5) ? depart_date + 1 : depart_date
# Final results
depart = depart_date + ' ' + depart_time
arrive = arrive_date + ' ' + arrive_time
我想找到在Ruby on Rails中实现此目标的最佳方法,而不仅仅是玩弄字符串.
I want to find the best way to implement this in Ruby on Rails, instead of just playing with strings.
推荐答案
这只是纯Ruby,与Rails无关:
This is just pure Ruby, nothing to do with Rails:
require 'date'
depart_time = DateTime.strptime '23:30', '%H:%M'
arrive_time = DateTime.strptime '02:15', '%H:%M'
arrive_date = depart_date = Date.parse( '2010-12-20' )
arrive_date += 1 if arrive_time.hour < depart_time.hour and arrive_time.hour < 5
puts "#{depart_date} #{depart_time.strftime '%H:%M'}",
"#{arrive_date} #{arrive_time.strftime '%H:%M'}"
#=> 2010-12-20 23:30
#=> 2010-12-21 02:15
这篇关于Ruby中的日期时间比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!