使用 Ruby on Rails 格式化日期 [英] Format the date using Ruby on Rails
问题描述
flickr api 提供发布日期作为 unix 时间戳一:发布日期始终作为 unix 时间戳传递,这是一个无符号整数,指定自格林威治标准时间 1970 年 1 月 1 日以来的秒数.
"
The flickr api provides a posted date as 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 对其进行格式化?
For example, here is the date '1100897479
'. How do I format it using Ruby on Rails?
推荐答案
一旦你解析了时间戳字符串并有一个时间对象(详见其他答案),你可以使用 Time.to_formatted_s 来自 Rails.它内置了多种格式,您可以使用符号指定这些格式.
Once you have parsed the timestamp string and have a time object (see other answers for details), you can use Time.to_formatted_s from Rails. It has several formats built in that you can specify with symbols.
引用:
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 是别名)
(Time.to_s is an alias)
您也可以定义自己的格式 - 通常在初始化程序中(感谢 Dave Newton 指出这一点).做法是这样的:
You can also define your own formats - usually in an initializer (Thanks to Dave Newton for pointing this out). This is how it's done:
# 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}") }
这篇关于使用 Ruby on Rails 格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!