我正在使用ruby。
我正在试图弄清如何将以下内容转换为:
14
变为 下午2点
0
变为 上午12点
23
变为 晚上11点
谢谢!
[14, 0, 23].map { |hour| Time.parse("#{hour}:00").strftime("%l %P") }
=> [" 2 pm", "12 am", "11 pm"]
我喜欢@Mori的答案,因为它让时间来承担沉重的工作,但使用Benchmark我们可以看到哪个是最占用CPU资源的:
下面是我写的:
def am_pm(hour)
meridian = (hour >= 12) ? 'pm' : 'am'
hour = case hour
when 0, 12
12
when 13 .. 23
hour - 12
else
hour
end
"#{ hour } #{ meridian }"
end
基准测试:
require 'benchmark'
require 'time'
def mori(hour)
Time.parse("#{hour}:00").strftime("%l %P")
end
def convert h
p, l = h.divmod(12)
"#{l.zero? ? 12 : l} #{p.zero? ? "a" : "p"}m"
end
def am_pm(hour)
meridian = (hour >= 12) ? 'pm' : 'am'
hour = case hour
when 0, 12
12
when 13 .. 23
hour - 12
else
hour
end
"#{ hour } #{ meridian }"
end
def hour_24_to_12(hour_24)
hour_12 = hour_24 - 12
if hour_12 == 0
return "12 pm"
elsif hour_12 == -12
return "12 am"
elsif hour_12 > 0
return "#{hour_12} pm"
elsif hour_12 < 0
return "#{hour_24} am"
else
# The passed-in time is outside the range o 0-23,
# so you may need to deal with this however you
# feel is appropriate
end
end
HRS = [0, 14, 23]
N = 100_000
puts RUBY_VERSION
HRS.each { |hr| puts "am_pm: #{ am_pm(hr) }" }
HRS.each { |hr| puts "convert: #{ convert(hr) }" }
HRS.each { |hr| puts "hour_24_to_12: #{ hour_24_to_12(hr) }" }
HRS.each { |hr| puts "mori: #{ mori(hr) }" }
Benchmark.bm(13) do |b|
b.report('am_pm') { N.times { HRS.each { |h| am_pm(h) } } }
b.report('convert') { N.times { HRS.each { |h| convert(h) } } }
b.report('hour_24_to_12') { N.times { HRS.each { |h| hour_24_to_12(h) } } }
b.report('mori') { N.times { HRS.each { |h| mori(h) } } }
end
这会输出:
1.9.3
am_pm: 12 am
am_pm: 2 pm
am_pm: 11 pm
convert: 12 am
convert: 2 pm
convert: 11 pm
hour_24_to_12: 12 am
hour_24_to_12: 2 pm
hour_24_to_12: 11 pm
mori: 12 am
mori: 2 pm
mori: 11 pm
user system total real
am_pm 1.230000 0.000000 1.230000 ( 1.228159)
convert 1.280000 0.000000 1.280000 ( 1.286672)
hour_24_to_12 0.640000 0.000000 0.640000 ( 0.642993)
mori 20.940000 0.020000 20.960000 ( 21.003620)
在仅使用 Ruby 2.0-p0 运行时的相同测试:
2.0.0
am_pm: 12 am
am_pm: 2 pm
am_pm: 11 pm
convert: 12 am
convert: 2 pm
convert: 11 pm
hour_24_to_12: 12 am
hour_24_to_12: 2 pm
hour_24_to_12: 11 pm
mori: 12 am
mori: 2 pm
mori: 11 pm
user system total real
am_pm 0.440000 0.000000 0.440000 ( 0.433303)
convert 0.410000 0.000000 0.410000 ( 0.412183)
hour_24_to_12 0.200000 0.000000 0.200000 ( 0.201894)
mori 9.910000 0.010000 9.920000 ( 9.921940)
def convert h
p, l = h.divmod(12)
"#{l.zero? ? 12 : l} #{p.zero? ? "a" : "p"}m"
end
convert(14) # => "2 pm"
convert(0) # => "12 am"
convert(23) # => "11 pm"
if int == 0
,if int > 12
和elseif
。我觉得这样会更可靠和符合你的需求。 - tmwoods2 pm
是什么?它是时间对象还是字符串或其他什么? - Joshua Cheek