使用Ruby on Rails设置日期格式

r1zhe5dt  于 2023-01-16  发布在  Ruby
关注(0)|答案(7)|浏览(163)

flickr API提供了一个发布日期作为unix timestamp one:“The posted date is always passed around as a unix timestamp, which is an unsigned integer specifying the number of seconds since Jan 1st 1970 GMT.
例如,下面是日期“1100897479”,我如何使用Ruby on Rails格式化它?

rjzwgtxy

rjzwgtxy1#

一旦解析了时间戳字符串并拥有了一个time对象(有关详细信息,请参阅其他答案),就可以使用Rails中的Time.to_formatted_s,它内置了几种格式,可以用符号指定。
引用:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"

(Time.to_s是别名)
你也可以定义你自己的格式--通常是在初始化器中(感谢Dave Newton指出这一点)。

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
cbjzeqam

cbjzeqam2#

我来回答这个问题,
所以首先你需要把时间戳转换成一个真实的Ruby日期/时间,如果你从facebook收到的只是一个字符串或int,你需要做如下的事情:

my_date = Time.at(timestamp_from_facebook.to_i)

好了,现在假设你已经有了约会对象......

**to_formatted_s**是一个方便的Ruby函数,可以将日期转换为格式化字符串。

下面是它的一些用法示例:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007    

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"    

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"

如您所见::db、:number、:short...是自定义日期格式。
要添加自己的自定义格式,可以创建以下文件:config/initializers/time_formats.rb并在其中添加您自己的格式,例如以下格式:

Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015

其中**:month_day_comma_year是格式的名称(您可以将其更改为任何您想要的名称),而%B %e,%Y**是unix日期格式。
这里有一个关于unix日期语法的快速备忘单,所以你可以快速设置你的自定义格式:

From http://linux.die.net/man/3/strftime    

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %e - Day of the month without leading 0 (1..31) 
  %g - Year in YY (00-99)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character    

   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"

希望这对你有帮助。我还把这个小指南做了一个github gist,以防有人喜欢。

h4cxqtbf

h4cxqtbf3#

Easiest is to use strftime (docs).
但是,如果要在视图侧使用它,最好将其 Package 在helper中。

72qzrwbm

72qzrwbm4#

@CMW的答案是正确的,我添加这个答案是作为一个例子,说明如何配置一个初始化器,以便Date和Time对象都获得格式
配置/初始化器/时间格式.rb

date_formats = {
  concise: '%d-%b-%Y' # 13-Jan-2014
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats

另外,下面两个命令将遍历当前环境中的所有DATE_FORMATS,并以每种格式显示今天的日期和时间:

Date::DATE_FORMATS.keys.each{|k| puts [k,Date.today.to_formatted_s(k)].join(':- ')}
Time::DATE_FORMATS.keys.each{|k| puts [k,Time.now.to_formatted_s(k)].join(':- ')}
piztneat

piztneat5#

请查看localizel
例如:

l Time.at(1100897479)
nszi6y05

nszi6y056#

首先你需要把时间戳转换成一个真实的Ruby日期/时间,如果你从facebook收到的只是一个字符串或int,你需要做如下的事情:

my_date = Time.at(timestamp_from_facebook.to_i)

然后,为了在视图中很好地格式化它,您可以使用to_s(默认格式):

<%= my_date.to_s %>

请注意,如果您不放置to_s,那么在视图或字符串中使用它时,默认情况下仍然会调用它。例如,以下代码也会在日期上调用to_s

<%= "Here is a date: #{my_date}" %>

或者如果你想用一种特定的方式来格式化日期(例如使用“d/m/Y”)-你可以使用strftime,就像另一个答案中概述的那样。

46scxncf

46scxncf7#

由于时间戳是从UNIX纪元开始的秒数,您可以使用DateTime.strptime(“字符串解析时间”)和正确的说明符:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

请注意,必须使用require 'date'才能使其正常工作,然后可以将其称为Date.strptime(如果只关心日期)或DateTime.strptime(如果您想要日期和时间)。如果您需要不同的格式,您可以在其上调用DateTime#strftime(如果您很难处理格式字符串,请查看strftime.net)或使用rfc822等内置方法之一。

相关问题