TimeDate格式化输出:
DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d %H:%M:%S').to_s #就是按照2013-8-16 16:42:13的格式输出
如果只想输出日期,而不要输出具体时间
DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d').to_s #就是按照2013-8-16格式输出
反向格式化(将字符串转化为日期格式):
DateTime.parse(params['date']).strftime('%Y-%m-%d %H:%M:%S').to_s
接下来介绍rails自带的TimeDate格式
如果你忘记了rails自带的TimeDate格式,那么在命令行输入:
> rake date_formats
执行命令后,可以看到如下
Date
====
db:'%Y-%m-%d' --
short:'%e %b' Dec
number:'%Y%m%d'
long:'%B %e, %Y' December ,
long_ordinal:'&proc' December 4th,
rfc822:'%e %b %Y' Dec DateTime
========
db:'%Y-%m-%d' -- ::
short:'%e %b' Dec :
number:'%Y%m%d'
long:'%B %e, %Y' December , :
long_ordinal:'&proc' December 4th, :
rfc822:'%e %b %Y' Fri, Dec :: + Time
====
short:'%d %b %H:%M' Dec :
db:'%Y-%m-%d %H:%M:%S' -- ::
number:'%Y%m%d%H%M%S'
long:'%B %d, %Y %H:%M' December , :
long_ordinal:'&proc' December 4th, :
rfc822:'%a, %d %b %Y %H:%M:%S %z' Fri, Dec :: 中国标准时间
time:'%H:%M' :
简单的格式化例子: Time.now.to_s(:db) #格式为2013-8-16
接下来介绍,集成多种方式输出
# config/initializers/date_time_formats.rb
Time::DATE_FORMATS.merge!(
:full => '%B %d, %Y at %I:%M %p',
:md => '%m/%d',
:mdy => '%m/%d/%y',
:time => '%I:%M %p'
)
简单的格式化例子:Time.now.to_s(:full) #格式为"August 16, 2013 at 17:32 PM"
要是要求是当前年份,不显示年,其他的年才显示
Time::DATE_FORMATS.merge!(
:friendly => lambda { |time|
if time.year == Time.now.year
time.strftime "%b #{time.day.ordinalize}"
else
time.strftime "%b #{time.day.ordinalize}, %Y"
end
}
)
>> Time.now.to_s(:friendly)
=> "August 16th"
>> (Time.now-2.years).to_s(:friendly)
=> "August 16th, 2011"