【问题标题】:Convert from timestamp to time [duplicate]从时间戳转换为时间[重复]
【发布时间】:2017-08-03 11:02:15
【问题描述】:

我正在尝试使用时间戳显示时间。下面是一个例子:

t = Time.at(1500999892331)
#=> 49534-10-18 04:02:11 +0530
t.to_date
#=> Thu, 18 Oct 49534

我得到一个错误的输出。请帮我解决这个问题。

【问题讨论】:

  • 哪一部分错了,什么是“正确”的输出?

标签: ruby-on-rails ruby datetime


【解决方案1】:

Ruby 的 Time.at 预计秒数(带分数)。根据定义

使用时间给定的值、seconds_with_fracsecondsmicroseconds_with_frac 自 Epoch 以来的给定数量创建一个新的 Time 对象。

您提供的值是毫秒。改成

Time.at(1500999892331/1000)
=> 2017-07-25 21:54:52 +0530
t.to_date
=> Tue, 25 Jul 2017

【讨论】:

    【解决方案2】:

    你可以这样做

    (Time.at(1500999892331/1000)+0530).strftime("%I:%M%p")
    #=> "10:00PM" 
    

    (Time.at(1500999892331/1000)+0530).strftime("%Y-%b-%d %I:%M%p")
    #=> "2017-Jul-25 10:00PM" 
    

    以下是您可以在strftime 方法中指定的一些日期和时间格式:

    Date (Year, Month, Day):
      %Y - Year with century (can be negative, 4 digits at least)
              -0001, 0000, 1995, 2009, 14292, etc.
      %C - year / 100 (round down.  20 in 2009)
      %y - year % 100 (00..99)
    
      %m - Month of the year, zero-padded (01..12)
              %_m  blank-padded ( 1..12)
              %-m  no-padded (1..12)
      %B - The full month name (``January'')
              %^B  uppercased (``JANUARY'')
      %b - The abbreviated month name (``Jan'')
              %^b  uppercased (``JAN'')
      %h - Equivalent to %b
    
      %d - Day of the month, zero-padded (01..31)
              %-d  no-padded (1..31)
      %e - Day of the month, blank-padded ( 1..31)
    
      %j - Day of the year (001..366)
    
    Time (Hour, Minute, Second, Subsecond):
      %H - Hour of the day, 24-hour clock, zero-padded (00..23)
      %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
      %I - Hour of the day, 12-hour clock, zero-padded (01..12)
      %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
      %P - Meridian indicator, lowercase (``am'' or ``pm'')
      %p - Meridian indicator, uppercase (``AM'' or ``PM'')
    
      %M - Minute of the hour (00..59)
    
      %S - Second of the minute (00..59)
    
      %L - Millisecond of the second (000..999)
      %N - Fractional seconds digits, default is 9 digits (nanosecond)
              %3N  millisecond (3 digits)
              %6N  microsecond (6 digits)
              %9N  nanosecond (9 digits)
              %12N picosecond (12 digits)
    

    【讨论】:

    • 我如何在这里获取日期?
    • @ShruthiR 答案已更新,请检查
    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 2014-04-11
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多