2012-08-26 34 views
1

這個問題是問幾乎與此相同:如何格式化Ruby on Rails中的日期和/或時間輸入?

除頂層外的答案是不是爲我工作。我對Ruby和RoR都很陌生,所以我不確定我到底在做什麼。這是我到目前爲止。

我已經添加了默認的日期和時間格式在我en.yml

en: 
    date: 
    formats: 
     default: '%d.%m.%Y' 
    time: 
    formats: 
     default: '%H:%M' 

我還添加了以下代碼的新初始化:

Date::DATE_FORMATS[:default] = '%d.%m.%Y' 
Time::DATE_FORMATS[:default] = '%H:%M' 

當我去鐵軌控制檯,並做Time.now.to_sDate.today.to_s我得到正確的結果。例如,從數據庫中提取並在模型索引頁上顯示時,這些也會正確顯示。

但是,當我嘗試創建具有某些日期和時間字段(不是日期時間!)的表單時,我得到日期的舊版本YYYY-MM-DD,以及整個YYYY-MM-DD HH:mm:ss.nnnnnn

正確格式化這些輸入值的最佳做法是什麼?我想避免在視圖中更改任何內容(如完成here),並在應用程序級別正確解決此問題 - 如果可能的話。

回答

1

這是我落得這樣做:

首先我定義模型中的自定義字段:

attr_accessible :entry_date_formatted 

    def entry_date_formatted 
    self.entry_date.strftime '%d.%m.%Y' unless self.entry_date.nil? 
    end 

    def entry_date_formatted=(value) 
    return if value.nil? or value.blank? 
    self.entry_date = DateTime.strptime(value, '%d.%m.%Y').to_date 
    end 

然後我從entry_date改變了我的形式entry_date_formatted

<%= form.text_field :entry_date_formatted, :placeholder => 'Date' %> 

最後但並非最不重要,我已將相關字段添加到我的區域設置文件中:

en: 
    activerecord: 
    attributes: 
     time_entry: 
     entry_date_formatted: Entry date 
     start_time_formatted: Start time 
     end_time_formatted: End time 

這可能不是最好的方法,但它現在對我很好。

相關問題