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"
Share:
12,562
Paul Phoenix
Author by

Paul Phoenix

Updated on June 08, 2022

Comments

  • Paul Phoenix
    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 this 03-06-2012 and the same is to be converted in String 03-06-2012 so that the jquery datepicker can take it.

    All this conversion needs to be done at view .html.erb

  • Paul Phoenix
    Paul Phoenix over 10 years
    well 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
    Alive Developer over 10 years
    you 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
    Paul Phoenix over 10 years
    Well 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
    Paul Phoenix over 10 years
    value="2012-03-06 00:00:00 UTC"
  • Alive Developer
    Alive Developer over 10 years
    It 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
    Paul Phoenix over 10 years
    yes it is running in development env. and the console is not giving me any error message related to this problem
  • Epigene
    Epigene about 9 years
    Not quite what the OP needs, but a straightforward way.