【问题标题】:Change time formate in rails更改 Rails 中的时间格式
【发布时间】:2014-10-03 12:08:23
【问题描述】:

我有一个包含分钟和秒的时间对象,例如“05:37”。我想知道一种将其转换为以下格式的方法:“5m 37s”。

【问题讨论】:

  • 我不知道 ruby​​-on-rails,但你应该为此使用正则表达式。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

如果我们谈论的是 Time 对象,这很简单:

 t=Time.now
 puts "#{t.min}m #{t.sec}s"
 =>15m 28s

如果你有一个字符串

 s="05:37"
 t=s.split(':').map{|i| i.to_i}
 puts "#{t.first}m #{t.last}s"
 =>5m 37s

或者更短

 s.split(':').map{|i| i.to_i}.join("m ")+"s"

【讨论】:

    【解决方案2】:

    虽然我同意建议strftime 的评论,但您也可以使用gsub

    "05:37".gsub(/(\d+):(\d+)/, '\1m \2s')
    #=> "05m 37s"
    

    如果您不想要前导零,则很容易摆脱。

    【讨论】:

      【解决方案3】:
      [your_time_object].strftime('%Mm %Ss').
      

      更多详情请尝试this

      【讨论】:

        【解决方案4】:

        没关系:

        [(total_response_time.to_i / counter_for_response_time.to_i) / 60 % 60, (total_response_time.to_i / counter_for_response_time.to_i) % 60].map { |t| t.to_s.rjust(2,'0') }.join('m ')
        

        对于以后想要像这样转换它的任何人。

        【讨论】:

        • 这与您的问题不同。什么是total_response_time、counter_response_time?
        • 以及更简洁的实现方式:(total_response_time.to_i / counter_for_response_time.to_i).tap{|t| s="#{t/60}m #{t%60}s"} 放 s
        • 这看起来不像是做任何事情的好方法,它看起来真的很混乱和复杂。如果你有一个 Time 对象,那么就像人们所说的那样,在它上面使用 strftime。
        猜你喜欢
        • 1970-01-01
        • 2013-07-26
        • 2015-09-12
        • 1970-01-01
        • 2017-07-21
        • 2022-01-23
        • 1970-01-01
        • 2015-10-19
        相关资源
        最近更新 更多