I am building a simple event system and i am having problem with rails time helper conversions. I want to be able to have a 12hour clock that has an output of something like 12:00am or 12:00pm using something like <%= event.start_at %> to give the time output in the 12hour clock format
If event.start_at is already a date or time object (e.g. an ActiveRecord instance) then you could do something like:
<%= event.start_at.to_s(:my_format) %>
You'd need to define :my_format in an initializer:
# config/initializers/date_and_time_formats.rb
Time::DATE_FORMATS[:my_format] = '%I:%M%P' # 12:30pm
You can tweak the format to your liking and use it over and over again using to_s(:my_format). #Dave Newton pointed out where to go for formatting above.
http://apidock.com/ruby/Time/strftime
Related
I have the following method
<%= message.created_at.strftime("%H:%M") %>
that currently returns 21:00
I need to display a Europe/Kiev time zone which is 3 hours ahead than usual Greenwich's time zone. How do I set it in the method input?
You can use a beautiful gem named "local_time". It takes care of local rendering of the time in your views. It has very nice documentation as well. Visit https://github.com/basecamp/local_time
If you stored time in your database in UTC than that time will always be in UTC when you fetch it. You need to display it according to user's local time zone. You have to do that using JavaScript, check this article.
Or if you need just Kiev time zone and nothing else you can do something like this:
<%= message.created_at.in_time_zone('Europe/Kiev').strftime("%H:%M") %>
I am calling the date a record was created at in a basic app running Rails 3.1.
<%= #issue.created_at %>
The above outputs the following timestamp:
2011-09-10 14:44:24 UTC
What is the simplest way of altering the way this displays? I would like something like this:
10 Sept. 2011
and then somehow call it again with a different format:
14:44
so I can call it twice and merge the two together:
10 Sept. 2011
14:44
The reason I want to call it twice rather than create a helper to format a two line date/time is to allow me to call the date in some places and just the time in others.
The simplest thing to do is to use the strftime function
# Day / Month / Year
#issue.created_at.strftime("%d %b. %Y")
# Hour:Min
#issue.created_at.strftime("%H:%M")
You could put those two calls in separate helpers if you find yourself doing it a lot.
I would use I18n. Take a look at some example http://guides.rubyonrails.org/i18n.html#adding-date-time-formats. It's a clean and flexible way of formatting dates and times.
<%= l(#issue.created_at, :format=>:your_format) %>
in locale YAML (app/config/locale/country_id.yml) you must declare
time:
formats:
your_format: '%d %b. %Y'
your_another_format: '%I:%M'
Date formatting should be declared inside your i18n YAML definition file for easy configure, and other date format could be found here
Check out http://www.foragoodstrftime.com/ for an easy way to customize date/time formatting #spike
You can do:
#issue.created_at.to_date.iso8601
to_s also takes format input argument:
http://apidock.com/rails/ActiveSupport/TimeWithZone/to_s
I'm working with an app for a concert tour website, where all times (announcement times, on-sale start times, and event start times) are local to each particular venue's time zone. I take the user entered date/time where applicable and run a before_filter to set the appropriate time zone so that everything is stored in the database in UTC. For the 'new' form and for displaying the times in index and show actions, no problem at all. When the data is brought back out of the database and into a view, I use in_time_zone to adjust per the particular venue.
The only issue is on the edit form. The date/time select is showing the data in UTC. When I'm working on the site, I mentally adjust, but for others it's confusing. I'd like to do something along the lines of:
<%= f.datetime_select :start_datetime.in_time_zone(#event.time_zone) %>
Or, in the controller:
def edit
#performance = Performance.find(params[:id])
#event = #performance.event
#performance.start_datetime = #performance.start_datetime.in_time_zone(#event.time_zone)
end
Then simply, <%= f.datetime_select :start_datetime %>.
Unfortunately, I haven't found the right way to do this. Do you have any ideas worth giving a shot?
Thank you very much.
You may use default method of datetime_select, as following:
%br
= f.label :req_sess_start, "Session starts at"
= f.datetime_select(:req_sess_start, :start_year => 2010, :ampm => true, :default => 0.days.from_now.in_time_zone(#timezone))
Because of the default value shown, client will assume that times has to be entered in his/her local timezone, but...
this value will be actually in the timezone default to your application (as provided in application.rb, and the default is UTC).
So, you would require some server side coding to convert it to correct value.
I'm not sure if I understand what you want to do, but since you're storing the #event.time_zone, you could add
:default => start_time.in_time_zone(#event.time_zone)
to your datetime_select form field.
How about something like this:
# change PST to correct zone abbrev.
new_zone = ActiveSupport::TimeZone.new("PST")
#performance.start_datetime = #performance.start_datetime.in_time_zone(new_zone)
I just noticed this is an old post but:
If I were you, I would use a virtual attribute to represent the date time of the venue. For instance, you could add an attribute to performance called adjusted_start_time.
In my view I want to display the current date in "mm/dd/yyyy" format.
<%= Time.now.strftime("%m/%d/%Y") %>
You could simply do (substitute in Time for DateTime if using straight Ruby -- i.e. no Rails):
DateTime.now.strftime('%m/%d/%Y')
If you're using that format a lot, you might want to create a date_time_formats initializer in your RAILS_ROOT/config/initializers folder (assuming Rails 2), something like this:
# File: date_time_formats.rb
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:human => "%m/%d/%Y"
)
Which will then let you use the more friendly version of DateTime.now.to_s(:human) in your code.
I think you can use .strftime:
t = Time.now()
t.strftime("The date is %m/%d/%y")
This should give "The date is 09/09/10". See here for a great list of the format codes for .strftime.
If you don't need the full year you could try
Time.now.strftime('%D')
I've been pulling my hair out trying to work with Time in Rails. Basically I need to set all time output (core as well as ActiveSupport) to the server's local time -- no GMT, no UTC, etc. I've seen various posts relating to Time, but they usually involve someone's need to set it for each user. Mine isn't nearly as complex, I simply want consistency when I use any Time object. (I'd also appreciate not receiving errors every 3 seconds telling me that I can't convert a Fixnum (or some other type) to string -- it's Ruby, just do it!)
I also seem to be getting drastically different times for Time.new vs the ActiveSupport 1.second.ago. Anyway, does anyone have any quality suggestions as regards working with Time in Rails?
If you just want Time objects to be consistent, then why not stick with UTC? I just tried Time.new and 1.second.ago using script/console and I get the same output (give or take a second for typing the command). How are you doing it?
Somewhere in your initializers, define the format(s) that you want to use.
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y %H:%M')
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:my_special_format => '%H:%M %p')
Then when you want to print a Time object, it works like the following example. Notice that the Time object in my console is already aware of my time zone. I'm not performing any magical transformations here.
>> t = Time.now
=> Wed Jul 15 18:47:33 -0500 2009
>> t.to_s
=> "07/15/2009 18:47"
>> t.to_s(:my_special_format)
=> "18:47 PM"
Calling Time#to_s uses the :default format, or you can pass in the name of the format you'd rather use like I did with :my_special_format.
You can see the various options for formatting a Time object here.
If u don't want to store each user time setting, the only solution is to use javascript time system because it work on user client time. For example i have an application that each time user try it, the app will create some example data with each data have a initial date value "today". At first time, it confuse me a lot because my host server is in australia and lot of user is on western part, so sometime the initial date value is not "today", it said "yesterday" because of different time region.
After a couple day of headache i finally take decision to JUST use javascript time system and include it in the link, so when user click the "try now" link it will also include today date value.
<% javascript_tag do -%>
var today = new Date();
$("trynow").href = "<%= new_invitation_path %>?today=" + today.toLocaleString();
<% end -%>
Add the following to config/environment.rb to handle time correctly and consistently all the time within the context of Rails. It's important to know that it will store your times to the database in UTC -- but this is what you want -- all the conversion is done automatically.
config.time_zone = 'Pacific Time (US & Canada)'
You can run rake time:zones:local from your Rails root directory to get a list of valid time zone strings in your area.
A quick addition to the DATE_FORMAT solution posted above. Your format can be a string, in which case it works as noted above by calling strftime, but you can also define the format as a lambda:
CoreExtensions::Time::Conversions::DATE_FORMATS.merge! :my_complex_format => lambda {|time|
# your code goes here
}