Ruby:将秒转换为自然语言

时间:2017-06-27 15:15:50

标签: ruby datetime format

我们如何将等待时间(以秒为单位)转换为自然表达人类等待时间的字符串?

示例输入&输出

  • 45 => '45秒'#如果不到一分钟,请在几秒钟内表达
  • 85 => '1分钟'#如果不到一个小时,请在几分钟内表达
  • 3745 => '直到今天下午5:45'#如果不到一天,则在一天中的时间表达四舍五入到最近的15分钟
  • 9342 => '直到星期二下午6:30'#如果不到一周,则在一周中表达,时间四舍五入到最近的15分钟
  • 139342 => '直到12/13/17在下午2:00'#no,表示日期和时间四舍五入到最近的15分钟

1 个答案:

答案 0 :(得分:1)

<强>代码

require 'time'

FMT = [[s =  60,         "%-S seconds",                   :NO_ROUND],
       [s *= 60,         "%-M minutes",                   :ROUND_MINS],
       [s *= 24,         "until %-l:%M %p today",         :ROUND_UP_MINS_15],
       [s *   7,         "until %A %-l:%M %p",            :ROUND_UP_MINS_15],
       [Float::INFINITY, "until %-_m/%d/%y at %-l:%M %p", :ROUND_UP_MINS_15]]

def fmt_duration(start_time = Date.today.to_time, elapsed_seconds)
  secs = start_time.to_i + elapsed_seconds
  _, fmt, round = FMT.find { |max_secs_plus_1, *_| elapsed_seconds < max_secs_plus_1 }
  rnd_secs =
  case round
  when :NO_ROUND
    secs
  when :ROUND_MINS
    mins = (secs/60.0).round
    mins -= 1 if mins % 60 == 0
    60 * mins
  when :ROUND_UP_MINS_15
    900 * (secs/900.0).ceil
  end
  Time.at(rnd_secs).strftime(fmt)
end

请注意

puts "#{FMT}"
  #=> [[60,       "%-S seconds",                   :NO_ROUND],
  #    [3600,     "%-M minutes",                   :ROUND_MINS],
  #    [86400,    "until %-l:%M %p today",         :ROUND_UP_MINS_15],
  #    [604800,   "until %A %-l:%M %p",            :ROUND_UP_MINS_15],
  #    [Infinity, "until %-_m/%d/%y at %-l:%M %p", :ROUND_UP_MINS_15]]

请参阅Time#strftime,了解Date第二列中TimeFMT格式代码的列表。

<强>实施例

def time_to_secs(days, hours, minutes, seconds)
  seconds + 60 * (minutes + 60 * (hours + 24 * days))
end

secs = time_to_secs( 0,  0,  0, 37) #=> 37
fmt_duration(secs)                  #=> "37 seconds"

secs = time_to_secs( 0,  0, 41, 37) #=> 2_497
fmt_duration(secs)                  #=> "42 minutes"

secs = time_to_secs( 0, 13, 41, 37) #=> 49_297
fmt_duration(secs)                  #=> "until 1:45 PM today"

secs = time_to_secs( 6, 23, 36, 37) #=> 603_397
fmt_duration(secs)                  #=> "until Tuesday 11:45 PM"

secs = time_to_secs(24, 13, 41, 37) #=> 2_122_897
fmt_duration(secs)                  #=> "until 7/22/17 at 1:45 PM"
相关问题