2014-09-24 20 views
0

下面的代碼工作,只顯示,如果它是目前日期:顯示格式的日期如果存在的話,否則佔位符

f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: @post.try(:published_at) 

但我會怎麼格式化?

這是我怎麼會格式化,如果我知道的日期存在:

value: @post.published_at.strftime("%e %b %Y") 
+2

你約'@ post.try(:published_at)。嘗試(:strftime的「% e%b%Y「)'? – IS04 2014-09-24 12:44:25

回答

1

裹繞一個輔助函數來更改格式

f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: custom_format(@post.try(:published_at)) 

some_helper.rb

def custom_format(date) 
    date ? date.strftime("%e %b %Y") : nil 
end 
1

你爲什麼不添加一個返回您的首選格式的日期,簡單的方法?

class YourModel 
    def formatted_published_at 
    published_at.strftime("%e %b %Y") if published_at? 
    end 
end 

除了窗體之外,您可能也會在其他視圖中使用它。