从时间戳转换为时间

时间:2017-08-03 11:02:16

标签: ruby-on-rails ruby datetime

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

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

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

2 个答案:

答案 0 :(得分:2)

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

  

创建一个新的Time对象,其值为time,给定的seconds_with_frac,或secondsmicroseconds_with_frac自Epoch以来。

您提供的值是毫秒。将其更改为

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

答案 1 :(得分: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)
相关问题