0

In my Ruby on Rails 4 app I need to convert user entered dates like...

25.07.2014
25/07/2014

...possibly even...

25-07-2014

...into a the default Date format that can be stored in MySQL database.

2014-07-25

How can this be done?

Thanks for any help.

3 Answers 3

1

Use strftime: http://www.ruby-doc.org/core-2.1.2/Time.html#method-i-strftime

date = Time.parse(params[:date])
date.strftime("'%Y-%m-%d'");
Sign up to request clarification or add additional context in comments.

Comments

1

Using String#sub or String#sub!, gsub or gsub!:

'25.07.2014'.sub(/(\d{2})\D(\d{2})\D(\d{4})/, '\3-\2-\1')
# => "2014-07-25"
'25/07/2014'.sub(/(\d{2})\D(\d{2})\D(\d{4})/, '\3-\2-\1')
# => "2014-07-25"

Comments

1

Use Time.parse, Luke. It covers all your examples.

>> require 'time'
=> true
>> Time.parse '25.07.2014'
=> 2014-07-25 00:00:00 +0200
>> Time.parse '25/07/2014'
=> 2014-07-25 00:00:00 +0200
>> Time.parse '25-07-2014'
=> 2014-07-25 00:00:00 +0200
>> Time.parse '2014-07-25'
=> 2014-07-25 00:00:00 +0200

More in the article Ruby for Admins: Date and Time

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.