Ruby - DateTime for Database
I have a Database column with the syntax "0000-00-00 00:00:00". In PHP I would do date('Y-m-d H:i:s');
In Ruby, I do
require 'date'
now = DateTime::now()
puts "#{now.year()}-#{now.mon()}-#{now.mday()} #{now.hour()}:#{now.min()}:#{now.sec()}"
The result is: "2010-1-5 10:16:4"开发者_运维技巧 That's not okay. How could I create a "timestring" with the format "0000-00-00 00:00:00"?
Thanks a lot in advance & Best Regards
You can format the dates like in PHP thanks to the built-in Time
class, see documentation there.
This would give for your case :
t = Time.now
puts t.strftime("%Y-%m-%d %H:%M:%S")
A little shorter
t = Time.now
puts t.strftime("%F %T")
=> "2015-01-06 14:01:05"
iso8601 method can be useful also:
>> Time.now.utc.iso8601
=> "2015-05-08T16:45:22Z"
If you're using Rails/ActiveSupport then to_s(:db) will be the shortest way:
Time.now.to_s(:db)
=> "2017-05-22 11:14:40"
ActiveRecord tends to store dates / times as UTC, so using utc
will make your data more consistant
t = Time.now.utc
puts t.strftime("%F %T")
=> "2016-05-06 19:05:01"
Note that Rails also stores microsecond precision. That is, microseconds are the 6 digits after the second in the database format:
Time.now.strftime('%Y-%m-%d %H:%M:%S.%6N')
=> "2022-10-26 12:30:26.243506"
or:
Time.now.strftime('%F %T.%6N')
=> "2022-10-26 12:34:37.803091"
精彩评论