humbargs
12/14/2013 - 3:10 PM

Ruby: Convert the Format of a Date

Ruby: Convert the Format of a Date

#!/opt/apps/ruby/ruby/bin/ruby
require 'date'

# The initial date format as a String
my_date = "2013-10-03 21:03:46Z"

# Convert the Date to a DateTime Object
date_obj = DateTime.strptime(my_date,'%Y-%m-%d %H:%M:%S%Z')

# Re-Format the date - returns a String
# You can find directives for formats in the ruby
# docs DateTime object
format   = date_obj.strftime('%Y-%m-%dT%H:%M:%S.%LZ')

# Output the Date
puts "Date : " + format.to_s
#!/opt/apps/ruby/ruby/bin/ruby
require 'date'

# The initial date format as a String
my_date = '10/02/2013'

# Convert the Date to a Date Object
date_obj = Date.strptime(my_date,'%m/%d/%Y')

# Output with some convenience methods
puts "Month: " + Date::MONTHNAMES[date_obj.month]
puts "Day: " + date_obj.day.to_s
puts "Year: " + date_obj.year.to_s
puts Date::MONTHNAMES[date_obj.month]
puts date_obj.day
puts date_obj.year