Thursday, May 02, 2013

Date Time Formatting in Ruby and Ruby on Rails


In develop any Ruby on Rails application, most of time we need to time calculation and different types of date time. Bellow i describe different types ruby date time format and rails date time format.

So open your rails console and test this bellow examples -

Rails Date Time helpers.



now = Time.now        #=> 2013-04-30 00:14:38 +0600
now + 10.seconds      #=> 2013-04-30 00:14:48 +0600
now + 10.minutes      #=> 2013-04-30 00:24:38 +0600
now + 1.hours         #=> 2013-04-30 01:14:38 +0600
now + 1.days          #=> 2013-05-01 00:14:38 +0600
now + 1.weeks         #=> 2013-05-07 00:14:38 +0600
now + 1.months        #=> 2013-05-30 00:14:38 +0600
now + 1.years         #=> 2014-04-30 00:14:38 +0600
now - 1.years         #=> 2012-04-30 00:14:38 +0600

Rails Date Time Calculations.


now.beginning_of_day   #=> 2013-04-30 00:00:00 +0600
now.beginning_of_week  #=>2013-04-29 00:00:00 +0600
now.beginning_of_month #=>2013-04-01 00:00:00 +0600
now.yesterday          #=>2013-04-29 00:14:38 +0600
now.prev_month         #=> 2013-03-30 00:14:38 +0600
now.prev_year          #=> 2012-04-30 00:14:38 +0600
now.end_of_day         #=>2013-04-30 23:59:59 +0600
now.end_of_week        #=> 2013-05-05 23:59:59 +0600
now.end_of_month       #=> 2013-04-30 23:59:59 +0600
now.end_of_year        #=> 2013-12-31 23:59:59 +0600
now.tomorrow           #=>2013-05-01 00:14:38 +0600
now.next_month         #=>2013-05-30 00:14:38 +0600
now.next_year          #=>2014-04-30 00:14:38 +0600

Ruby Date Time Formatting.


now = Time.now                          #=>2013-04-30 00:38:26 +0600
now.strftime("%m/%d/%Y")                #=> "04/30/2013"
now.strftime("%I:%M%p")                 #=> "12:38AM"
now.strftime("%Y-%d-%m")                #=>"2013-30-04"
now.strftime("%Y-%m-%d")                #=>"2013-04-30"
now.strftime("%y-%m-%d")                #=>"13-04-30"
now.strftime("%d %B %Y")                #=>"30 April 2013"
now.strftime("%d %b %Y")                #=>"30 Apr 2013"
now.strftime("%A, %d %b %Y")            #=>"Tuesday, 30 Apr 2013"
now.strftime("%a %d %b %Y")             #=>"Tue 30 Apr 2013"
now.strftime("%Y-%m-%d %H:%M:%S %p")    #=>"2013-04-30 00:38:26 AM"
now.strftime("%Y-%m-%d %H:%M:%S %p %z") #=>"2013-04-30 00:38:26 AM +0600"

Rails Date Time Formatting.


now = Time.now          #=>2013-04-30 00:58:05 +0600
now.to_s(:db)           #=> "2013-04-30 00:58:05"
now.to_s(:number)       #=> "20130430005805"
now.to_s(:time)         #=> "00:58"
now.to_s(:short)        #=> "30 Apr 00:58"
now.to_s(:long)         #=> "April 30, 2013 00:58"
now.to_s(:long_ordinal) #=>"April 30th, 2013 00:58"