Date string conversion

I have a date string: "2009-10-12". I would like to write a method that takes this as a parameter and returns the three letter day of the week (in this case "mon"). I wrote this:

def date_to_day_of_week(date)
  d = Date.parse(date).strftime("%a").downcase!
  return d
end

      

When I call this from the script / console, it works as expected. However, when I call this from my application, I get a lot of different errors depending on what I am doing. The main problems are that either date_to_day_of_week

the method is undefined, or if I move the content of the method (i.e. day = Date.parse(date).strftime("%a").downcase!

inline, then I get private method gsub! called for Mon, 12 Oct 2009:Date

). I just think I start to understand Ruby and Rails and then I go back to the beginning!

Can anyone help with this?

Woof

+2


source to share


6 answers


Where is this code located? If, for example, this is in a model called by the controller, you can go with:

def self.date_to_day_of_week(date)
  d = Date.parse(date).strftime("%a").downcase!
  return d
end

      



And call it in your controller with:

def index
  # ...
  @date = Model.date_to_day_of_week("2009-12-30")
end

      

+2


source


Have a look at ActiveSupport :: CoreExtensions :: Date :: Conversions. You can define your own DATE_FORMATS and output it with "to_formatted_s". I believe you want the abbreviated month to be "% b"



+1


source


If you get an "undefined" error, it means that this method is not available from the moment it was called.

If you are trying to call it from a helper, you need to put this method in your ApplicationHelper, not in ApplicationController. If you also want it to be accessible from your controllers, inject the following into your ApplicationController:

helper_method :date_to_day_of_week

      

0


source


say dt = Time.now () dt.strftime ("% A") gives you the day

0


source


try it

def date_to_day_of_week(date)
  Date.parse(date).strftime("%a").downcase
end

      

Ruby returns the last value evaluated in the method, so you don't need to specifically return anything. Same! in lower case! just changes the value of the string it was called on, instead of returning the value as you would expect.

0


source


You tried

day = Date.parse (date) .strftime ("% a"). to_s .downcase

Date methods work slightly differently within rails versus ruby, due to ActiveSupport

0


source







All Articles