【问题标题】:How to get 2 digit hour and minutes from Rails time class如何从 Rails 时间类中获取 2 位数的小时和分钟
【发布时间】:2012-07-04 03:19:08
【问题描述】:

我在看

http://corelib.rubyonrails.org/classes/Time.html#M000245

如何从时间对象中获取两位数的小时和分钟

假设我愿意

t = Time.now

t.hour // this returns 7 I want to get 07 instead of just 7

同样的

t.min //  // this returns 3 I want to get 03 instead of just 3

谢谢

【问题讨论】:

    标签: ruby-on-rails datetime


    【解决方案1】:

    值得一提的是,您可能需要特定时区的小时数。

    如果时区已经设置(无论是全局的还是你在一个区块内):

    Time.current.to_formatted_s(:time)
    

    内联设置时区:

    Time.current.in_time_zone(Location.first.time_zone).to_formatted_s(:time)
    

    【讨论】:

      【解决方案2】:

      不管怎样,to_formatted_s 实际上有一个更短的别名 to_s

       Time.now.to_s(:time)
      

      【讨论】:

        【解决方案3】:

        你可以试试这个!

        Time.now.to_formatted_s(:time)
        

        【讨论】:

          【解决方案4】:

          如果你想把你的时间组合成一个可读的字符串或类似的东西,可能值得研究Time#strftime

          例如,

          t = Time.now
          t.strftime('%H')
            #=> returns a 0-padded string of the hour, like "07"
          t.strftime('%M')
            #=> returns a 0-padded string of the minute, like "03"
          t.strftime('%H:%M')
            #=> "07:03"
          

          【讨论】:

            【解决方案5】:

            使用String.format (%) 运算符怎么样?像这样:

            x = '%02d' % t.hour
            puts x               # prints 07 if t.hour equals 7
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-11-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-06-16
              • 2014-05-31
              相关资源
              最近更新 更多