Ruby - DateTime for the database

I have a database column with the syntax "0000-00-00 00:00:00". In PHP, I would do date ('Ymd 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()}"

Result: "2010-1-5 10: 16: 4" This is not normal. How can I create a "timestring" in the format "0000-00-00 00:00:00"?

Many thanks and best regards

+5
source share
5 answers

You can format dates like in PHP, thanks to the built-in class Time, see the documentation there .

This will give you your case:

t = Time.now
puts t.strftime("%Y-%m-%d %H:%M:%S")
+9
source

A bit shorter

t = Time.now
puts t.strftime("%F %T")

=> "2015-01-06 14:01:05" 
+2
source

iso8601 :

>> Time.now.utc.iso8601
=> "2015-05-08T16:45:22Z"
+2

ActiveRecord / UTC, utc

t = Time.now.utc
puts t.strftime("%F %T")

=> "2016-05-06 19:05:01"
0
source

If you use Rails / ActiveSupport, to_s (: db) will be the shortest way:

Time.now.to_s(:db)
=> "2017-05-22 11:14:40"
0
source

All Articles