转换字符串时间以查找 Time.now ~ Ruby 在 Rails 上的时间差
Converting string time to find difference in time from Time.now ~ Ruby on Rails
我有这种格式的时间“20:10 PM”,我需要找出 Time.now
与给定时间
之间的区别
例如,如果 Time.now
说 2022-05-17 18:32:52.133290553 -0700
,我需要找出今天同一天的 Time.now
和“20:10 PM”之间的区别。
我无法在 Rails 上找到任何关于 Ruby 的参考资料。
假设您总是想将 Time.now
与今天的某个时间进行比较(即今天的 20:30),您可以为要比较的时间构建一个新的 Time
实例.
todays_year = Time.now.year
todays_month = Time.now.month
todays_day = Time.now.day
time_to_compare = Time.new(todays_year, todays_month, todays_day, 20, 30) # 20 and 30 represent the dynamic time you want to compare
time_diff = ((Time.now - time_to_compare) / 3600).round(2) # assuming you want to know the difference in hours and rounded to 2 decimal places
很简单的方法:
>> Time.now - Time.parse("20:10 PM")
=> 10995.706874
如果没有给出日期,Time.parse
将采用今天的日期。返回结果以秒为单位。
我有这种格式的时间“20:10 PM”,我需要找出 Time.now
与给定时间
例如,如果 Time.now
说 2022-05-17 18:32:52.133290553 -0700
,我需要找出今天同一天的 Time.now
和“20:10 PM”之间的区别。
我无法在 Rails 上找到任何关于 Ruby 的参考资料。
假设您总是想将 Time.now
与今天的某个时间进行比较(即今天的 20:30),您可以为要比较的时间构建一个新的 Time
实例.
todays_year = Time.now.year
todays_month = Time.now.month
todays_day = Time.now.day
time_to_compare = Time.new(todays_year, todays_month, todays_day, 20, 30) # 20 and 30 represent the dynamic time you want to compare
time_diff = ((Time.now - time_to_compare) / 3600).round(2) # assuming you want to know the difference in hours and rounded to 2 decimal places
很简单的方法:
>> Time.now - Time.parse("20:10 PM")
=> 10995.706874
如果没有给出日期,Time.parse
将采用今天的日期。返回结果以秒为单位。