2017-08-03 200 views
-1

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

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

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

+1

哪一部分是错的,一个nd什么是“正确的”输出? – sawa

回答

2

Ruby的Time.at预计秒(含分数)。每定义

创建以来大纪元给定数的seconds_with_frac,或secondsmicroseconds_with_frac由时间给出的值,一个新的Time对象。

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

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

你可以这样做

(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) 
+1

我怎样才能在这里得到日期? –

+0

@ShruthiR回答更新请检查 –