我在db中有一个datetime列,当我向用户展示它时,我想将其转换为简单的日期。在Ruby on Rails中将DateTime转换为简单的日期
我该怎么做?
def shown_date # to_date does not exist, but is what I am looking for self.date || self.exif_date_time_original.to_date end
我在db中有一个datetime列,当我向用户展示它时,我想将其转换为简单的日期。在Ruby on Rails中将DateTime转换为简单的日期
我该怎么做?
def shown_date # to_date does not exist, but is what I am looking for self.date || self.exif_date_time_original.to_date end
DateTime#to_date
不具有的ActiveSupport存在:
$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
from (irb):1
>> require 'active_support/core_ext'
=> true
>> DateTime.new.to_date
=> Mon, 01 Jan -4712
)`.to_date()`在标准ruby中不存在是一件很遗憾的事情,所以我们必须做一个解决方法。 DateTime和Date的内部是不容易的。只是肆意的,忽略!:-) – Notinlist 2010-09-03 08:56:08
你好collimarco :)你可以使用红宝石的strftime方法来创建自己的乌尔日期/时间显示。
time.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)
%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"
我最近写了一个宝石来简化这一过程,并neaten了你的观点,等等等等
在Ruby 1.9.2和上述他们增加了.to_date函数为DateTime:
http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date
此实例方法似乎不存在于像1.8.7这样的早期版本中。
尝试先将条目转换为字符串。只要数据库列类型是一个日期,它就会被格式化为日期。
self.date || self.exif_date_time_original.to_s
对于老红宝石(1.8.x的):
myDate = Date.parse(myDateTime.to_s)
你只是想格式化吗? – 2009-07-10 15:57:31
不,我想创建一个Date对象 – collimarco 2009-07-10 16:02:15
Ooops ..愚蠢的问题! to_date DO EXISTS! 对不起( – collimarco 2009-07-10 16:07:18