例如有个时间t = Time.now,格式化有:
t.to_s(:long)
t.to_s(:short)
t.to_s(:db)
还可以调用strftime方法加以参数:
参看其参数,运行:ri Time.strftime
Format meaning:
%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)
%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"
这样可以自定义时间格式。
这个可以显示所调用的时间点距离现在的时间差:
def relative_time
diff_seconds = (Time.now - self).to_i
case diff_seconds
when 0 .. 59
"#{diff_seconds}秒钟前"
when 60..(3600-1)
"#{diff_seconds/60}分钟前"
when 3600..(3600*24-1)
"#{diff_seconds/3600}小时前"
when (3600*24)..(3600*24*30)
"#{diff_seconds/(3600*24)}天前"
else
self.strftime("%Y-%m-%d")
end
end
这是网上的一段代码:
module PrettyDate
def to_pretty
a = (Time.now-self).to_i
case a
when 0 then return 'just now'
when 1 then return 'a second ago'
when 2..59 then return a.to_s+' seconds ago'
when 60..119 then return 'a minute ago' #120 = 2 minutes
when 120..3540 then return (a/60).to_i.to_s+' minutes ago'
when 3541..7100 then return 'an hour ago' # 3600 = 1 hour
when 7101..82800 then return ((a+99)/3600).to_i.to_s+' hours ago'
when 82801..172000 then return 'a day ago' # 86400 = 1 day
when 172001..518400 then return ((a+800)/(60*60*24)).to_i.to_s+' days ago'
when 518400..1036800 then return 'a week ago'
end
return ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
end
end
Time.send :include, PrettyDate