Rails Date Format (To match YYYY-MM-DD HH-MM-SS)

时间:2015-07-31 20:23:52

标签: ruby-on-rails ruby-on-rails-4

When I do this:

DateTime.now.to_s

I get: 2015-07-31T22:22:05+02:00

But I need it in this format:

2015-07-31 22:22:05

How can I format it this way?

3 个答案:

答案 0 :(得分:13)

Since this is a common thing to want, there is a shorthand method to do this.

DateTime.now.to_s(:db)     #=> 2015-07-31 22:22:05

http://api.rubyonrails.org/classes/DateTime.html#method-i-to_formatted_s

答案 1 :(得分:8)

DateTime.now.strftime("%Y-%m-%d %I:%M:%S")

DateTime strftime method

答案 2 :(得分:7)

You can use strftime function for formatting your dates

DateTime.now.strftime('%Y-%m-%d %I:%M:%S')

View here