Skip to content

Instantly share code, notes, and snippets.

@cowboy-cod3r
Created December 14, 2013 15:10
Show Gist options
  • Save cowboy-cod3r/7960349 to your computer and use it in GitHub Desktop.
Save cowboy-cod3r/7960349 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment