Thursday, 13 December 2007

Display DateTime in client side Time zone


suppose you want to convert datetime in client side(browser) time zone and display it.
example take events, Events have date so that event date first you have to store it in database as GMT timezone
then write javascript function for onload event like this
function events()
{
var currentDate = new Date();
var offset = currentDate.getTimezoneOffset().toString();
new Ajax.Updater(‘events’, ‘/events/load_events?offset=’ + offset, {asynchronous:true, evalScripts:true}); return false;
}
The events.rhtml will be like this
<h1>Events</h1>
<div id=”events”></div>
In third line of javascript I am making an ajax call with updating “events” div tag.
This ajax will call the action “load_events” in controller “events”
events_controller.rb
def load_events
@events = Event.find(:all)
@offset = params[:offset].to_i
end
In view “load_evevnts.rhtml” calculate date with offset
<ul>
<% @events.each do |e| %>
<li><%= e.name %> on <%= (e.date – offset) %></li>
<% end %>
</ul>

Wednesday, 12 December 2007

Formating date Time in Rails


You can format Date field by using strftime function
example :
Time.now()
=> Wed Dec 12 15:48:59 +0530 2007
Time.now().strftime("%d/%m/%y %H:%M")
=> "12/12/07 15:50"
Here's the (shortened) table for strftime.
%a  weekday name.
%A  weekday name (full).
%b  month name.
%B  month name (full).
%c  date and time (locale)
%d  day of month [01,31].
%H  hour [00,23].
%I  hour [01,12].
%j  day of year [001,366].
%m  month [01,12].
%M  minute [00,59].
%p  AM or PM
%S  Second [00,61]
%U  week of year (Sunday)[00,53].
w  weekday [0(Sunday),6].
W  week of year (Monday)[00,53].
x  date (locale).
%X  time (locale).
%y  year [00,99].
%Y  year [2000].
%Z  timezone name.