有时你可能会忘了rails中定义的一些日期时间格式,或许你会忘了自己加入的一些日期时间格式。
下面的代码将会列出rails中的日期时间格式。
task :date_formats => :environment do now = Time.now [:to_date, :to_datetime, :to_time].each do |conv_meth| obj = now.send(conv_meth) puts obj.class.name puts "=" * obj.class.name.length name_and_fmts = obj.class::DATE_FORMATS.map { |k, v| [k, %Q('#{String === v ? v : '&proc'}')] } max_name_size = name_and_fmts.map { |k, _| k.to_s.length }.max + 2 max_fmt_size = name_and_fmts.map { |_, v| v.length }.max + 1 name_and_fmts.each do |format_name, format_str| puts sprintf("%#{max_name_size}s:%-#{max_fmt_size}s %s", format_name, format_str, obj.to_s(format_name)) end puts end end
到项目目录下执行rake date_formats,可以看到如下的输出:
Date ==== db:'%Y-%m-%d' 2009-12-04 short:'%e %b' 4 Dec number:'%Y%m%d' 20091204 long:'%B %e, %Y' December 4, 2009 long_ordinal:'&proc' December 4th, 2009 rfc822:'%e %b %Y' 4 Dec 2009 DateTime ======== db:'%Y-%m-%d' 2009-12-04 15:38:38 short:'%e %b' 04 Dec 15:38 number:'%Y%m%d' 20091204153838 long:'%B %e, %Y' December 04, 2009 15:38 long_ordinal:'&proc' December 4th, 2009 15:38 rfc822:'%e %b %Y' Fri, 04 Dec 2009 15:38:38 +0800 Time ==== short:'%d %b %H:%M' 04 Dec 15:38 db:'%Y-%m-%d %H:%M:%S' 2009-12-04 15:38:38 number:'%Y%m%d%H%M%S' 20091204153838 long:'%B %d, %Y %H:%M' December 04, 2009 15:38 long_ordinal:'&proc' December 4th, 2009 15:38 rfc822:'%a, %d %b %Y %H:%M:%S %z' Fri, 04 Dec 2009 15:38:38 中国标准时间 time:'%H:%M' 15:38