在Rails中格式化日期

时间:2017-10-30 05:29:15

标签: ruby-on-rails ruby

如何格式化此日期时间属性2017-10-15或如何获取当月的第15个?

@today = Time.now
@mid = time.strftime("%Y-%m-15")

进入October 15, 2017?我尝试使用to_formatted_s(:long),但它给出了未定义方法的错误。

3 个答案:

答案 0 :(得分:1)

Mydate = "2017-10-15"
Mydate.to_date.strftime("%B %d, %Y")
=> "October 15, 2017"

答案 1 :(得分:1)

在Rails 4或以上

> Date.today.beginning_of_month + 14
#=> Sun, 15 Oct 2017 
# formatted as per your requirement
> (Date.today.beginning_of_month + 14).strftime("%B %d, %Y")
#=> "October 15, 2017"

Date#beginning_of_month 它会返回指定日期的月份开始日期(始终为1st,添加14 days),这样您就会获得{{ 1 {} 15th

答案 2 :(得分:0)

使用@GaganGami解决方案,您可以创建Date类方法middle_of_current_month

class Date
  def self.middle_of_current_month
    (today.beginning_of_month + 14).strftime("%B %d, %Y")
  end
end

Date.middle_of_current_month
#=> "October 15, 2017"