Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 395
Tim Avatar asked Jan 05 '10 09:01

Tim


2 Answers

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")
like image 101
glmxndr Avatar answered Sep 20 '22 05:09

glmxndr


A little shorter

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

=> "2015-01-06 14:01:05" 
like image 30
Mark Swardstrom Avatar answered Sep 23 '22 05:09

Mark Swardstrom