Forum: Ruby on Rails date.to_s trimming

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
32833d3ac17df58279c087afe3f7cf92?d=identicon&s=25 Mike Schwab (mschwab)
on 2006-01-23 02:09
When I convert a datetime to a string, it prints out something like this

Jan 20 12:00:00 EST 2006

I want to trim off the last twelve characters, i.e.

:00 EST 2006

I tried to do it like so:

@date =
@meeting.date.to_s.chomp.chomp.chomp.chomp.chomp.chomp.chomp.chomp.chomp.chomp.chomp.chomp

but the chomps seem to do nothing.  I'd love to use regex, but I don't
know which method to use to remove text from a string, or to just sever
the end of it (I tried unshift).
6076c22b65b36f5d75c30bdcfb2fda85?d=identicon&s=25 Ezra Zygmuntowicz (Guest)
on 2006-01-23 02:23
(Received via mailing list)
On Jan 22, 2006, at 5:09 PM, Mike Schwab wrote:

>
>
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>


Mike-

	Check out ri strftime in your shell it will show you a ton of
options for formatting times and dates. Here's an example to do what
you want:

in irb:

 >> Time.now.strftime("%b %d %I:%M")
=> "Jan 22 05:23"


Cheers-

-Ezra Zygmuntowicz
WebMaster
Yakima Herald-Republic Newspaper
ezra@yakima-herald.com
509-577-7732
Af93ba6b6b59f22a8f37e8de5702ef98?d=identicon&s=25 Bob Silva (Guest)
on 2006-01-23 02:48
(Received via mailing list)
The response below would be the right way to do it, but to clear some
things
up for you:

To get a substring:
"Jan 20 12:00:00 EST 2006"[0..11]

or

"Jan 20 12:00:00 EST 2006"[0...12] => Jan 20 12:00

And as a bonus, if you had used chop() instead of chomp(), your example
would have worked, but that would be real bad! :)

Hope this helps in the future, for now, use the strftime like Ezra
showed.

Cheers,

Bob Silva
37b7b848b1e3d667174d28d32d04bcee?d=identicon&s=25 Charles M. Gerungan (Guest)
on 2006-01-23 17:50
(Received via mailing list)
On 23-jan-2006, at 2:09, Mike Schwab wrote:

> When I convert a datetime to a string, it prints out something like
> this
>
> Jan 20 12:00:00 EST 2006
>
> I want to trim off the last twelve characters, i.e.
>
> :00 EST 2006

In config/environment.rb
require_dependency  'datetime_formats'

In lib/datetime_formats.rb
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
   :my_date             => '%b %d %I:%M',      # your format
   :long_datetime       => '%a %d-%m-%Y %H:%M' # add more if needed
)

In your view:
<%= object.method.to_s(:my_date) %>

--
Regards, Charles.
This topic is locked and can not be replied to.