views:

1284

answers:

5

I am a RoR newbie. I tried a lot of things, finally came to following:

<td>
 <%= Date.strptime(request.baseline_start_date, "%Y-%M-%D %H:%M:%S %Z").strftime("%M/%D/%Y")%>
</td>

But this is also giving me an error:

$_ value need to be String (nil given)

But I know that request.baseline_start_date gives me value (tried printing it separately). I don't know which one it is saying as nil given.

Any suggestions on how I can achieve format conversion?

+1  A: 

What I have done is add an initializer named conversions.rb in config/initializer After that Add a line like follows:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.update(:<name> => '<formatting>')

From there on you can render your datetime using your format with:

dateVar.to_s(:<name>)

There is a handy list here of the formatting tokens

Chad Ruppert
A: 

Thanks a lot for the reply. My problem is, the output seems to be already string and i have to convert from date in string to another format.

When I look at the date stored in database (Oracle) it is mm/dd/yy, but when i get it displayed, it adds the timestamp and timezone.

I tried setting the default in Configuration\environment.rb as ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!( :default => '%d %b %Y' ) But that also doesn't seem to help.

At the end, if I just get the string to convert from Timezone format to mm/dd/yyyy, that is enough.

A: 

You can use the String#to_time (or Date#to_time) function in ActiveSupport to convert the string into a Time (or Date) object. Then use strftime as you have already.

insane.dreamer
A: 
Date.strptime(
  "2009-04-24 18:33:41 UTC",
  "%Y-%m-%d %H:%M:%S %Z"
).strftime("%m/%d/%Y")
# => "04/24/2009"

I think maybe you just got the capitalization on your format strings wrong.

Bob Aman
+1  A: 

Ive written a really nice gem that simplifies the whole process, and makes date formatting DRY.

Check it out at: http://github.com/platform45/easy_dates

Ryan