【问题标题】:Ruby: Convert seconds to natural languageRuby:将秒转换为自然语言
【发布时间】:2017-11-30 17:24:40
【问题描述】:

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

示例输入和输出

  • 45 => '45 seconds' # 如果小于一分钟,以秒表示
  • 85 => '1 minute' # 如果少于一小时,则以四舍五入的分钟数表示
  • 3745 => '直到今天下午 5:45' # 如果少于一天,则以一天中的时间表示,四舍五入到最接近的 15 分钟
  • 9342 => '直到星期二下午 6:30' # 如果少于一周,则以星期几表示,时间四舍五入到最接近的 15 分钟
  • 139342 => '直到 2017 年 12 月 13 日下午 2:00' # 否则,以日期和时间表示,四舍五入到最接近的 15 分钟

【问题讨论】:

  • 你在使用 Rails 吗?
  • @SaraTibbetts rails 助手没有涵盖这个用例,因为它是针对“时间之前”而不是“时间之前”。
  • @ma111hew28 - 我认为不存在这方面的宝石。但您可以将其实现为一系列 if 语句,就像您的问题一样。
  • 您的要求非常具体。如果有内置助手,我会感到惊讶。
  • @eiko 可以转换时间以使其正常工作

标签: ruby datetime format


【解决方案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 以获取FMT 第二列中Date 和Time 格式代码的列表。

示例

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"

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2014-05-23
    • 2012-09-17
    • 1970-01-01
    相关资源
    最近更新 更多