2010-07-23 23 views
2

在我的應用程序中,我希望時間/日期顯示爲月/年(例如7/10)。問題是,有時我得到一流的日期,有時上課時間,所以我風與應用程序控制器下面的代碼...日期和時間ROR

class Date 
    def as_month_and_year 
    self.strftime("%m").to_i.to_s + self.strftime("/%y") 
    end 
end 

class Time 
    def as_month_and_year 
    self.strftime("%m").to_i.to_s + self.strftime("/%y") 
    end 
end 

什麼變幹這件事的最佳方式?

回答

1

恕我直言更優雅的解決方案:

module DateTimeExtensions 
    def as_months_and_year 
    self.strftime('%m/%y').sub(/^0/,'') 
    end 
    [Time, Date, DateTime].each{ |o| o.send :include, self } 
end 
+0

它很優雅,但擴展了三個內置的Ruby類,這是一種簡單的視圖關注點,在這種情況下,恕我直言過量。 – 2010-07-23 16:00:08

+0

這是railsway:http://github.com/rails/rails/tree/master/activesupport/lib/active_support/core_ext/ – jigfox 2010-07-23 16:04:41

+0

我完全知道ActiveSupport模塊提供了Ruby類的各種有用的擴展,但那是因爲Rails是一個*框架*。它還爲這種類型的問題提供了視圖幫助器機制。 – 2010-07-23 16:09:17

1

也許這樣?

module DateTimeExtensions 
    def as_month_and_year 
    self.strftime("%m").to_i.to_s + self.strftime("/%y") 
    end 
end 

class Date; include DateTimeExtensions; end 
class Time; include DateTimeExtensions; end 
class DateTime; include DateTimeExtensions; end 
+0

而且短一些具有:'self.month + self.strftime( 「/%y」)' – Brian 2010-07-23 16:52:27

2

我會創建一個接受日期或時間實例並適當格式化的視圖幫助方法。無需重新打開日期和時間類。這種事情正是視圖幫助模塊的目的。

def as_month_and_year(date) 
    date.strftime("%m").to_i.to_s + self.strftime("/%y") 
end 

然後在你的觀點,你可以只使用:

<%= as_month_and_year(@object.created_at) 
+0

'date.strftime(「%m /%y」)'!='self.strftime(「%m」).to_i.to_s + self.strftime(「/%y」)'它不會刪除前導零點 – jigfox 2010-07-23 15:52:52

+0

好的結果,我編輯了我的答案。 – 2010-07-23 15:54:52