T
T
The Whiz2013-11-21 16:03:37
PostgreSQL
The Whiz, 2013-11-21 16:03:37

How to replace strftime in Rails after switching to Postgres?

Switched from SQLite to PG and to constructions like:
@today = Date.today.strftime("%d.%m.%Y")
or

def self.query_by_year_month(y, m)
  where("strftime('%Y', date) = ? and strftime('%m', date) = ?", y, m)
end

I'm catching
PG::UndefinedFunction: ERROR:  function strftime(unknown, date) does not exist

Googling a little, I saw that Postgres does not know the strftime method, but it knows to_char, date_part, etc., but for the life of me, I don’t understand how to use it. Please tell me how to use this method in Rails!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sdevalex, 2013-11-21
@modernstyle

def self.by_month(month)
  dt = DateTime.new(month) # на случай если строку передают
  where("published_at >= ? and published_at <= ?", dt.beginning_of_month, dt.end_of_month)
end
Post.by_month(DateTime.new(1970, 1))

A
Andrey Chernomyrdin, 2013-11-26
@chernomyrdin

def self.query_by_year_month(y, m)
  where("date_part('year', date) = ? and date_part('month', date) = ?", y, m)
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question