Rails convert string containing datetime to date
12,562
Solution 1
Date.parse("2012-03-06 00:00:00 UTC").strftime("%d-%m-%Y")
Solution 2
You can do this
date = DateTime.now
puts date.to_date.to_s
which gives "2013-08-21"
Solution 3
date = Date.parse('2012-03-06 00:00:00 UTC')
# => Tue, 06 Mar 2012
date.strftime('%d-%m-%Y')
# => "06-03-2012"
Author by
Paul Phoenix
Updated on June 08, 2022Comments
-
Paul Phoenix almost 2 years
I have a String which contains the following string
2012-03-06 00:00:00 UTC
I want to change it into a date object so that is should look like this03-06-2012
and the same is to be converted in String03-06-2012
so that the jquery datepicker can take it.All this conversion needs to be done at view .html.erb
-
Paul Phoenix over 10 yearswell I am newbie to front end and rails both when I do the given below it works <%= text_field_tag map1[:field_name], "#{Date.parse("2012-03-06 00:00:00 UTC").strftime("%d-%m-%Y")}"%> but when i try using a variable instead of that hard coded value it breaks <%= text_field_tag map1[:field_name], "#{Date.parse("value").strftime("%d-%m-%Y")}", :class => 'blr', :placeholder => map1[:field_codes], :class =>"datepicker"%>
-
Alive Developer over 10 yearsyou should tell me the exact error it gives, and also the content of your value variable. Be sure your variable name isn't inside double quotes
-
Paul Phoenix over 10 yearsWell as I already told I am a newbie. How can I check what error is thrown at view. It just fails to load
-
Paul Phoenix over 10 yearsvalue="2012-03-06 00:00:00 UTC"
-
Alive Developer over 10 yearsIt should not fail to show, it should print the error at browser. Is your project running in development environment?. You could, elseway, look if the output of rails s in console tells you anything
-
Paul Phoenix over 10 yearsyes it is running in development env. and the console is not giving me any error message related to this problem
-
Epigene about 9 yearsNot quite what the OP needs, but a straightforward way.